python - How to write every 12th line to a new file -


i want select every 12th line in file , write lines new file. have suggestion? have 126 lines, first 6 lines header, need select 7th, 19th , 31st line , on until end of file reached. , every 10 lines selected should go new file.

the way code written can write 1 file, p_1 made of 10 (every 12th) lines 7,19,31...,109 want make 12 files though. first file p_1 starts @ 7th line, p_2 start @ 8th line. how loop through 7 8 , on, line 18?

i included in range write new 12 files (will work?).

for in range (1,12): open('output%i.txt' %i,'w+') g: dont know how lines change correspond correct file. ya know mean?

thanks again!

if have large file, approach doesn't load whole file memory. (as for line in f.readlines() would)

from itertools import islice #used 7th, 19th, etc... lines import fileinput #to iterate on lines without loading whole file memoru  open('output.txt','w+') g:     line in islice(fileinput.input('file.txt'),6,none,12): #start @ 6 because iterable 0-indexed, 7th element has index 6         g.write(line) 

or (method pointed out @elazar)

with open('output.txt', 'w') g, open('file.txt') f:     line in islice(f,6,none,12):         g.write(line) 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -