Python 将文本文件转换为字符串或列表

Python 将文本文件转换为字符串或列表,python,python-3.x,string,list,text-files,Python,Python 3.x,String,List,Text Files,我的文本文件中有以下数据: 5*0423257736326 8*2456773 我想用python处理数据。所以,我猜最好将其转换为字符串或列表 我使用了以下代码: a = open('test.txt', 'r') b = a.readlines() c = [x.replace('\n','') for x in b] print(c) 但它给出了: ['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3'] 我想知道如何将其转换

我的文本文件中有以下数据:

5*0423257736326

8*2456773

我想用python处理数据。所以,我猜最好将其转换为字符串或列表

我使用了以下代码:

a = open('test.txt', 'r')
b = a.readlines()
c = [x.replace('\n','') for x in b]
print(c)
但它给出了:

['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3']
我想知道如何将其转换为以下内容:

['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']
试试这个

a = open('test.txt', 'r')
b = a.readlines()

new_list = []
for line in b:
    for item in line.strip().split():
        new_list.append(item)
print(new_list)

我会将其转换为列表压缩并编辑帖子,但这里没有

a = open('test.txt', 'r')
b = a.readlines()
c = [a for n in str(b).split('\n') for a in n.split(' ') if a != '']
print(c)

>>> ['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']

你可以这样做

c=['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3']
c=[j for i in c for j in i.split()]
print(c)
输出

['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']

我只需通过
read
方法更改
readlines
(不将行拆分为不同的列表项),然后按空格更改
'\n'
换行符,最后按空格拆分字符串

a = open('test.txt', 'r')
b = a.read()
c = b.replace('\n', ' ').strip().split(' ')
a.close()
print(c)
我建议使用
with
语句,以免忘记关闭文件

with open('test.txt', 'r') as a:
    b = a.read()
c = b.replace('\n', ' ').strip().split(' ')
print(c)

我使用
with
方法打开并读取文件,同时使用
.read()
方法读取整个文件,而不是一次读取一行,然后
.split()
方法在每个
'
处拆分字符串,返回一个列表。

谢谢您的回复。我测试了这个,问题是当删除“\n”['5*0','4','3','2','5','7','7','3','6','3','2','6','8*2','4','5','6','7','8','7','3','7','3']时,它会生成空元素“”,为什么不干脆
a.read().split()
?谢谢你的回答,这一个给了我这个错误:“列表”对象没有属性“拆分”,请立即尝试,需要将其转换为字符串谢谢您的回复,是的,它工作得很好。谢谢
 with open('test.txt') as file: 
        print(file.read().split())