-2

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

2 Answers2

0

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.

TuDatTr
  • 41
  • 2
  • Thank you sir! Almost what I wanted the problem is that the files does appear like: a b c –  Nov 24 '20 at 17:41
  • Just ommit the `.rstrip()` from line 3. Then the characters should be below each other. And use `split(':\n')` instead of `split(':')` to delete the first empty line. – TuDatTr Nov 24 '20 at 17:52
  • Would you like to edit the code? I did like this: split_alph = "".join([i.rstrip() for i in f]).split('\n:')[:-1] , but it did not give me any file. Appreciate you time! @TuDatTr –  Nov 24 '20 at 18:04
  • I just edited the code, the new solution is without a lot of unnecessary bits. – TuDatTr Nov 24 '20 at 18:06
0
file = open("C:/Users/ASUS/Desktop/tutl.py" , "r") # This is input File
text = file.read()  # Reading The Content of The File.
file.close()  # Closing The File
splitted = text.split(":")  # Creating a List ,Containing strings of all Splitted part.

destinationFolder = "path_to_Folder" # Replace this With Your Folder Path

for x in range(len(splitted)):   # For loop for each parts
    
    newFile = open(destinationFolder + "/File"+str(x)+".txt" , "w")        # Creating a File for a part.
    newFile.write(splitted[x])                        # Writing the content
    newFile.close()                                   # Closing The File
riishiiraz
  • 31
  • 2