Python Forum
write each line of a text file into separate text files and save with different names - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: write each line of a text file into separate text files and save with different names (/thread-16253.html)



write each line of a text file into separate text files and save with different names - Shameendra - Feb-20-2019

Hi guys, I have a text file which contains the following value:
Output:
('Yellow_Hat_Person', [293, 997, [...]], [328, 1031, [...]]) ('Yellow_Hat_Person', [292, 998, [...]], [326, 1032, [...]]) ('Yellow_Hat_Person', [290, 997, [...]], [324, 1030, [...]]) ('Yellow_Hat_Person', [288, 997, [...]], [321, 1028, [...]]) ('Yellow_Hat_Person', [286, 995, [...]], [319, 1026, [...]])
I want to write each line into separate text files and save them with a different names. eg. line 1 should be passed to a text file and it should be saved as 1.txt, line to should be passed to a different text file and it should be saves ad 2.txt, line 3 passed to a different text file and saved as 3.txt and so on. Any suggestions would be helpful.


RE: separate the lines of a text file and write them into new separate text files - buran - Feb-20-2019

what have you tried? For start - take a look at our tutorial on working with files


RE: write each line of a text file into separate text files and save with different names - Shameendra - Feb-20-2019

nvm. I solved it by enumerating over the lines in the file. My code :

with open("Result.txt") as f:
    for i, line in enumerate(f):
        with open(f"{i+1}.txt", "w") as g:
            g.write(line)



RE: write each line of a text file into separate text files and save with different names - buran - Feb-20-2019

enumerate takes optional start argument. So you can write
with open("Result.txt") as f:
    for i, line in enumerate(f, start=1):
        with open(f"{i}.txt", "w") as g:
            g.write(line)