I'm fairly new to python and I am trying to write a script which reads x lines from a file and then writes that to new file. I would like it to iterate over all the subsequent lines writing to separate new files each time. The first 7 lines need to go in every new file.
Example format of the file to read is below:
Line 1: Data for EVERY new file
...
...
Line 8: Data to write to file one
...
...
Line 49: Data to write to file two
...
...
I have tried using itertools.islice but am not sure how to loop it for subsequent lines as well as into new files each time.
Sample code:
import os
from itertools import islice
#os.chdir("directory where XDATCAR is")
#ignore if .py is in the same directory
with open('XDATCAR' , 'r') as f:
for line in islice(f, 2, 7,):
print(line, end='')
with open('POSCAR','w') as n:
n.writelines()
I get the error:
ValueError: I/O operation on closed file.
Which I understand to be because 'with' closes the file after execution.
What I would like as output for each new file:
File 1:
First 7 lines of read file
lines 8 to 48
File 2:
First 7 lines of read file
lines 49 to 89
...
etc