1

I have some .txt files in a folder. I need to collect their content all in one .txt file. I'm working with Python and tried:

import os

rootdir = "\\path_to_folder\\"

for files in os.walk(rootdir):
    with open ("out.txt", 'w') as outfile:
         for fname in files:
             with open(fname) as infile:
                  for line in infile:
                      outfile.write(line)

but did not work. The 'out.txt' is generated but the code never ends. Any advice? Thanks in advance.

2 Answers2

2

os.walk returns tuples, not filenames:

with open ("out.txt", 'w') as outfile:
    for root, dirs, files in os.walk(rootdir):
        for fname in files:
             with open(os.path.join(root, fname)) as infile:
                  for line in infile:
                      outfile.write(line)

Also you should open outfile in the beginning, not in each loop.

Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
0

This solved my problem. The generated 'out.txt' file is just 151KB.

file_list = os.listdir("\\path_to_folder\\")

with open('out.txt', 'a+') as outfile:
for fname in file_list:
    with open(fname) as infile:
        outfile.write(infile.read())

Thanks everybody.