2

I use this code to list all those txt that are in the directory of the indicated path

from glob import glob

path_directory = 'Part001/*.txt'
list_files = glob(path_directory)

for f in list_files:
    print(f)

I need help to be able to merge all the listed txt into a single txt that contains all the text lines. Something like this:

In 31Aug21.txt

Hello
Hello!
Hello, Tell me about something

In 04Sep21.txt

Computer equipment has evolved in recent decades.
Perfect Orbit

In 05Sep21.txt

The sky is blue
the computer is really useful

And all the lines of the listed txt should be written in a new txt, like this:

Hello
Hello!
Hello, Tell me about something
Computer equipment has evolved in recent decades.
Perfect Orbit
The sky is blue
the computer is really useful

2 Answers2

1
from glob import glob

path_directory = 'Part001/*.txt'
list_files = glob(path_directory)

final = open('final_file.txt')
for f in list_files:
    with open(f) as fo:
        text = fo.read()
    final.write(text) #can add \n after this if you want - text+'\n'

final.close()
MohitC
  • 4,541
  • 2
  • 34
  • 55
0

Try this with reading the files...:

from glob import glob

path_directory = 'Part001/*.txt'
list_files = glob(path_directory)

lst = []
for fname in list_files:
    with open(fname, 'r') as f:
        lst.append(f.read())

with open('newfile.txt', 'w') as newf:
    newf.write('\n'.join(lst))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114