Search code examples
python-3.xfor-looptext-filesfile-writingfile-read

Code in python that writes more than one text-file


I have started with a code that is intended to write many textfiles by first reading one textfile. More details of question after the started code.

The textfile (Im reading from texfile called alphabet.txt):

a

b

c

:

d

e

f

:

g

h

i

:

I want the result to be like this:

file1:

a

b

c

file2:

d

e

f

file3:

g

h

i

enter code here
 
with open('alphabet.txt', 'r') as f:
    a = []
    for i in f:
        i.split(':')
        a.append(a)

The code is of course not done. Question: I don't know how to continue with the code. Is it possible to write the textfiles and to place them in a specific folder and too maybe rename them as 'file1, file2...' without hardcoding the naming (directly from the code)?


Solution

  • You could implement that function with something like this

    if __name__ == '__main__':
        with open('alphabet.txt', 'r') as f:
            split_alph = f.read().split(':\n')
            for i in range(len(split_alph)):
                x = open(f"file_{i}", "w")
                x.write(split_alph[i])
                x.close()
    

    Depending on whether there is a last : in the alphabet.txt file, you'd have to dismiss the last element in split_alph with

    split_alph = f.read().split(':\n')[:-1]
    

    If you got any further questions regarding the solution, please tell me.