0

我有一个类似于以下的 txt 文件

例子.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  
4

1 回答 1

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)))
于 2013-07-23T23:52:04.593 回答