我有一个类似于以下
的txt文件example.txt中
9987.000 2300 23 40 30
9654.988 1234 34 32 19
我想迭代这个文件并将其重写到另一个文件sample.txt中,如下所示,每个数字在它们自己的行上垂直列出,并按水平列出。
9987.000
2300
23
40
30
我是Python的新手,并不确定哪种方法可以做到这样的最佳方法。任何意见是极大的赞赏。 语法错误
File "Sample.py", line 64
with open('testFile.txt')as infile, open('testFile.txt','w') as outfile:
^
SyntaxError: invalid syntax
答案 0 :(得分:0)
对于大文件:
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
for line in infile:
for num in line.strip().split():
outfile.write(num + '\n')
对于小文件:
import itertools
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
outfile.write('\n'.join(itertools.chain.from_iterable(line.strip().split() for line in infile)))