2

I have a text file which contains the following value:

('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. The language i am using is python3

1 Answer 1

2

You loop over the lines of the file, and create a file for each line:

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

If you are on an older Python 3 version (3.5 and below), you replace the third line with

        with open("{}.txt".format(i+1), "w") as g:
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.