我想选择文件中的每个第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行?
我会在范围内包含i来编写新的12个文件(这会起作用吗?)。
对于范围内的i(1,12): 打开('输出%i.txt'%i,'w +')为g:我只是不知道如何更改行以使它们与正确的文件对应。你知道我的意思吗?
再次感谢!
答案 0 :(得分: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)
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)
答案 1 :(得分:3)
with open("input") as f:
for i, line in enumerate(f):
if (i-7) % 12 == 0: print line.rstrip("\n")
答案 2 :(得分:1)
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)
答案 3 :(得分:0)
# 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))