-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"?

  • all the data has to be same in all those 500 text files ? or you have a plan to supply data from other data structure ? – cruisepandey Aug 31 '21 at 13:52
  • No. "user", "time" and "note" change every time. It's just the pattern the same all the times. Every file text should have the same pattern with different data – Salvatore Pennisi Aug 31 '21 at 13:54
  • TEXT1: User=Name1; Time= time1; Note= note1; ------- TEXT2: User=Name2; Time= time2; Note= note2; and so on – Salvatore Pennisi Aug 31 '21 at 13:58
  • 1
    Welcome to Stack Overflow! Please take the [tour], read [what's on-topic here](/help/on-topic), [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953), and provide a [mre]. "Implement this feature for me" is off-topic for this site because SO isn't a free online coding service. You have to _make an honest attempt_, and then ask a _specific question_ about your algorithm or technique. – Pranav Hosangadi Aug 31 '21 at 14:12

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
  • 12,661
  • 3
  • 20
  • 33
  • 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