我想选择文件中的每 12 行并将这些行写入一个新文件。有人有建议吗?我有 126 行,前 6 行是标题,所以我需要选择第 7、19 和 31 行,依此类推,直到到达文件末尾。并且每选择 10 行应该进入一个新文件。
代码的编写方式 我可以编写一个文件,比如 P_1,它由 10(每 12 行)7、19、31...、109 行组成,不过我想制作 12 个文件。所以第一个文件是 P_1,从第 7 行开始,P_2 从第 8 行开始。我如何循环从 7 到 8 等等,最终到第 18 行?
我会将 for i 包含在写入新的 12 个文件的范围内(这行得通吗?)。
对于范围 (1,12) 中的 i: with open('output%i.txt' %i,'w+') as g: 我只是不知道如何更改行,以便它们与正确的文件相对应。你明白我的意思吗?
再次感谢!
最佳答案
如果您有一个大文件,这种方法很好,因为它不会将整个文件加载到内存中。 (因为 for line in f.readlines()
会)
from itertools import islice #used to get the 7th, 19th, etc... lines
import fileinput #to iterate over lines without loading whole file into memoru
with open('output.txt','w+') as g:
for line in islice(fileinput.input('file.txt'),6,None,12): #start at 6 because iterable 0-indexed, that is the 7th element has index 6
g.write(line)
OR(@Elazar指出的方法)
with open('output.txt', 'w') as g, open('file.txt') as f:
for line in islice(f,6,None,12):
g.write(line)
关于python - 如何将每 12 行写入一个新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16533838/