How can I create a new file for each n line occurance
I have a data like this:
ID 1
x y
3 4
4 3
6 8
ID 2
x y
3 4
4 3
6 8
.
.
.
ID 100
x y
2 40
41 32
6 8
I want to create a data file for each ID like ID_1.txt, ID_2.txt... My code is :
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
###############################################
fichier = "data.txt"
file = open(fichier).read().split('\n')
n =0
j=0
id=[]
for i in file :
# print("********",i)
current_id = j+1
if 'ID' in i:
id.append(n+1)
print('n=',n)
globals()[f'ID_{n}']=[]
n+=1
while current_id == id[-1] :
if i.find('ID'):
print(i.find('ID'))
eval()[f'ID_{n}'].append(i)
I'm still getting an ampty ID_{n} list, any idea?
Thanks.
You are on the right track, but you are making it too complicated. Open the file for reading and iterate through the lines, check for 'ID'
in the line to open a new file for writing.
from io import StringIO
# just make a generic file-like object to start with
writer = StringIO()
with open('data.txt') as fp:
for line in fp:
if line.startswith('ID'):
writer.close()
filename = line.strip().replace(' ', '_') + '.txt'
writer = open(filename, 'w')
writer.write(line)
writer.close()