繁体   English   中英

如何将第12行写入新文件

[英]How to write every 12th line to a new file

我想选择文件中的第12行并将这些行写入新文件。 有人有建议吗? 我有126行,前6行是标题,因此我需要选择第7、19和31行,依此类推,直到到达文件末尾。 并且每10行应选择一个新文件。

代码的编写方式我可以编写一个文件,例如P_1,它由10(每12个)行7,19,31 ...,109组成,但是我想制作12个文件。 因此,第一个文件是从第7行开始的P_1,而P_2从第8行开始。 我如何循环从7到8,依此类推,最终到达18行?

我会在范围内为我写新的12个文件(行得通吗?)。

对于范围(1,12)中的i: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)

(@Elazar指出的方法)

with open('output.txt', 'w') as g, open('file.txt') as f:
    for line in islice(f,6,None,12):
        g.write(line)
with open("input") as f:
    for i, line in enumerate(f):
        if (i-7) % 12 == 0: print line.rstrip("\n")
with open('newfile.txt', 'w') as outfile, open('input.txt') as infile:
    newfile.writelines(k for i, k in enumerate(infile) if i%12==7)
# creating the file as a base for me, you don't need this part
with open('dan.txt','w') as f:
    f.write('\n'.join(str(i) for i in xrange(1,127)))



# your desired code
with open('dan.txt') as g:
    li = g.readlines()

for i in xrange(6,19):
    with open('P_%d.txt' % (i-5),'w') as f:
        f.writelines(li[x] for x in xrange(i,126,12))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM