簡體   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