一开始就知道行数。
输入文件:
0 1 2 3 4 5 6 7 8
8 1 2 3 4 5 6 7 0
4 0 8 2 6 3 7 1 5
..n such lines预期结果:
line1 = [0, 1, 2, 3, 4, 5, 6, 7, 8]
line2 = [8, 1, 2, 3, 4, 5, 6, 7, 0]
line3 = [4, 0, 8, 2, 6, 3, 7, 1, 5]
.
.
linen = [n1, ........ n9]我现在:
代码:
#The lines start at the 7th byte in the input file.
f.seek(7)
#Getting rid of the '\r\n'
lines = [line.rstrip('\n\r') for line in f]
#1st line
line0 = lines[0]
line = [[int(i) for i in line0.split()]]
print line
...& so on for the 'n' lines发布于 2015-07-12 01:23:25
str.split()已经从末尾删除了空格,包括一个换行符。不需要删除\r;Python已经将行分隔符转换为\n。
不要尝试为多个line*变量赋值;只需使用列表:
with open(filename, 'r') as fobj:
all_lines = [[int(num) for num in line.split()] for line in fobj]现在,您有了一个带有整数的列表。
您可以在从文件中读取每一行时处理它;此时移向最终产品,而不是将所有行保存在内存中:
with open(filename, 'r') as fobj:
for line in fobj:
numbers = [int(num) for num in line.split()]
# do something with this line of numbers before moving on to the next.https://stackoverflow.com/questions/31363453
复制相似问题