2 回答

TA贡献1876条经验 获得超6个赞
尝试这个:
with open('data.txt') as fp, open('output.txt', 'w') as fw:
data = fp.read().replace('\n', ' ').split()
for i in range(0, len(data) // 10):
fw.write(' '.join(data[i * 10: (i + 1) * 10]) + '\n')
输出:
2623 831 6892 0 2353 1803 3425 0 1910 1823
3810 0 1637 1287 2811 0 2803 546 6609 0
1591 2157 2367 0 2167 1906 2665 0 3192 2168
8362 0 3903 1465 2011 0 2355 1801 2004 0
2390 796 5055 0 1703 1044 3441 0 1886 1328
2731 0 1496 1277 3074 0 1827 460 5992 0
1945 1785 2065 0 1983 1963 2818 0 1532 2229
6936 0 2449 5972 1918 0 2699 2007 1581 0

TA贡献1829条经验 获得超13个赞
不依赖于将整个文件读入内存的版本:
def get_words(f):
for line in f:
for word in line.split():
yield word
def chunk_values(iterator, num):
while True:
yield [next(iterator) for _ in range(num)]
with open('input.txt') as fin, open('output.txt', 'w') as fout:
for chunk in chunk_values(get_words(fin), 10):
fout.write(' '.join(chunk) + '\n')
添加回答
举报