1

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

我会将 for i 包括在范围内以编写新的 12 个文件(这行得通吗?)。

for i in range (1,12): with open('output%i.txt' %i,'w+') as g: 我只是不知道如何让行更改,以便它们与正确的文件相对应。你知道我的意思吗?

再次感谢!

4

4 回答 4

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)

(@Elazar 指出的方法)

with open('output.txt', 'w') as g, open('file.txt') as f:
    for line in islice(f,6,None,12):
        g.write(line)
于 2013-05-14T01:54:35.497 回答
3
with open("input") as f:
    for i, line in enumerate(f):
        if (i-7) % 12 == 0: print line.rstrip("\n")
于 2013-05-14T01:45:47.217 回答
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)
于 2013-05-14T02:09:57.810 回答
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))
于 2013-05-14T23:36:34.200 回答