您好,我想从文本文件文本导入数据.txt并将其导入到删除逗号和的数组中。文件的数据类似于以下内容:
1,2,3,4,5,6,7,8,9,0
0,9,8,7,6,5,4,3,2,1
3,5,2,7,6,5,5,2,6,1
1,2,3,4,5,6,7,8,9,0
0,9,8,7,6,5,4,3,2,1
0,9,8,7,6,5,4,3,2,1
3,5,2,7,6,5,5,2,6,1
到目前为止,我的代码如下:
def ReadFile():
myFile = open('text.txt','r')
lines = myFile.readlines()
print lines #print raw data
lines[:] = [line.rstrip('n') for line in lines]
print lines #print lines after removing n
lines = lines.replace(",", "")
print lines #print after removing commas
lines = map(int, lines)
print lines #print lines after converting to int
我无法删除逗号,也无法转换为 int。错误消息如下:
AttributeError: 'list' object has no attribute 'replace'
ValueError: invalid literal for int() with base 10: '1,2,3,4,5,6,7,8,9,0'
谢谢
你使这变得比必要的更难:
def ReadFile():
array = []
with open('textfiledata.txt', 'rt') as myFile:
for line in myFile:
array.append(map(int, line.split(',')))
return array
print ReadFile()
输出:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
[3, 5, 2, 7, 6, 5, 5, 2, 6, 1],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
[3, 5, 2, 7, 6, 5, 5, 2, 6, 1]]
试试这个:
def read_file(filename):
with open(filename) as f:
return [ [int(item) for item in line.split(',')]
for line in f ]
>>> print read_file('text.txt')
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
[3, 5, 2, 7, 6, 5, 5, 2, 6, 1],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
[3, 5, 2, 7, 6, 5, 5, 2, 6, 1]]
使用生成器,您可以执行以下操作:
# create a generator
def ReadFile():
with open('text.txt','r') as myFile:
for line in myFile:
# send out the line just processed
yield map(int, line.strip().split(','))
# cast the generator to a list for printing
print list(ReadFile())
您可以执行以下操作,因为您可以使用逗号和 int 强制转换:
for i in lines:
my_list.append(i)