Search code examples
pythonfiletext

How can I batch-export each line of a text file as its own separate text file?


I have a text file that constitutes a "database" of Pokemon information, formatted like so:

Bulbasaur  ๐—š๐—ฟ๐—ฎ๐˜€๐˜€๐Ÿƒ  ๐—ฃ๐—ผ๐—ถ๐˜€๐—ผ๐—ป๐Ÿงช
Ivysaur  ๐—š๐—ฟ๐—ฎ๐˜€๐˜€๐Ÿƒ  ๐—ฃ๐—ผ๐—ถ๐˜€๐—ผ๐—ป๐Ÿงช
Venusaur  ๐—š๐—ฟ๐—ฎ๐˜€๐˜€๐Ÿƒ  ๐—ฃ๐—ผ๐—ถ๐˜€๐—ผ๐—ป๐Ÿงช
Charmander  ๐—™๐—ถ๐—ฟ๐—ฒ๐Ÿ”ฅ  

... and so on.

What I would like to do is turn this text file into 1025 different text files (one for each line), with each text file named the first word of the line (eg Bulbasaur.txt, Ivysaur.txt).

It seems like this isn't something I can accomplish with Notepad++ alone, and I've searched here and seen some answers that suggest Python code, which tends to look something roughly like this:

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)

All of the answers I've seen are designed in such a way that the text files are named according to the line number, though (eg 0001.txt, 0002.txt), and I need the filenames to be the first word of each line. I'm not a programmer and I'm not familiar at all with Python; what would I have to do to pull this off?

Thank you!


Solution

  • You can use the string split() function to split text into separate words.

    with open("text_file.txt") as f:
        for line in f:
            parts = line.split()
            name = parts[0]
            with open(f"{name}.txt", "w") as g:
                g.write(line)