如何将每12行写入一个新文件

1 python file

我想在文件中选择每个第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行?

我会在范围内包括写入新的12个文件(这会起作用吗?).

对于范围内的i(1,12):打开('输出%i.txt'%i,'w +')为g:我只是不知道如何更改线条以使它们与正确的文件对应.雅知道我的意思吗?

再次感谢!

Hen*_*nyH 6

如果你有一个大文件,这种方法很好,因为它不会将整个文件加载到内存中.(如此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)
Run Code Online (Sandbox Code Playgroud)

(@Elazar指出的方法)

with open('output.txt', 'w') as g, open('file.txt') as f:
    for line in islice(f,6,None,12):
        g.write(line)
Run Code Online (Sandbox Code Playgroud)