-2

I have a text that repeat the same pattern of lines. like that:


 "User= Name1; 
  Time= HH:MM; 
  Note= example.
  User= Name2; 
  Time= HH:MM; 
  Note= example2.
  ......"   

this pattern is repeated 500 times.

how can i create 500 different text files, each for each "user"?

1 Answers1

1

It looks like each segment is 7 lines long, so you can read the data into a list, the use zip and iter to break it into a list of lists, each list being 7 elements long. Then you can write each one of those to a file.

If you are curious how zip(iter) works check out the details here

with open('users.txt') as f:
    data = f.readlines()
       
for c, file in  enumerate(zip(*[iter(data)]*7)):
    with open(f'file_{c}.txt', 'w') as f:
        f.writelines(file)

Or if you want the files names by the users

with open('users.txt') as f:
    data = f.readlines()
       
for file in zip(*[iter(data)]*7):
    name = file[0].split('=')[-1].split(';')[0].strip()
    print(name)
    with open(f'file_{name}.txt', 'w') as f:
        f.writelines(file)
Chris
  • 15,819
  • 3
  • 24
  • 37
  • 1
    It was so easy! Thank you a lot! – Salvatore Pennisi Aug 31 '21 at 14:14
  • Also, instead of answering questions that demonstrate no effort on OP's part, I'd suggest a better strategy to deal with such questions is to add a comment pointing them in the right direction, and flag to close. Giving OP the code they are asking for doesn't help them because they won't learn, and it doesn't help the community because it encourages more basic questions without showing their research/coding effort. – Pranav Hosangadi Aug 31 '21 at 14:15