-2

I am looking to put a bunch of text files into one directory, then create a new text file with all the files combined. Any help would be great!

arturo823
  • 1
  • 1
  • 2
    Welcome to SO! Please take the [tour] and read [ask]. What have you already tried? What exactly do you need help with? – wjandrea Mar 30 '20 at 15:54
  • 1
    Does this answer your question? [Python concatenate text files](https://stackoverflow.com/questions/13613336/python-concatenate-text-files) – U880D Mar 30 '20 at 16:41
  • What have you tried so far? Please post a code snippet. – David Hempy Mar 30 '20 at 19:56
  • I am so sorry, this was very rude of me. The first solution worked wonderfully! I turned a one hour project into a 2 minute solution! Once again my apologies for not commenting sooner. – arturo823 Apr 05 '20 at 01:49

2 Answers2

0

I think you want to put the txt files in a folder into a single txt file. You can fix the paths and try this code:

import os

text_file_path = "text_files"
text_files = [os.path.join(text_file_path,x) for x in os.listdir(text_file_path)]
output_file = open("output.txt","w")

for text_file in text_files:
    for line in open(text_file).readlines():
        output_file.write(line)
output_file.close()
0

The code below should do the job. This assumes that the files in your directory are text files.

import os

TARGET_DIR = "/path/to/your/directory"
OUTPUT_FILE_PATH = "/path/to/output.txt"

with open(OUTPUT_FILE_PATH, 'w') as output_file:
    # iterate over all files in the directory
    for _file in os.listdir(TARGET_DIR):
        file_path = os.path.join(TARGET_DIR, _file)

        # write file into output file
        with open(file_path, 'r') as f:
            output_file.write(f.read())
            output_file.write('\n')
ibaguio
  • 2,298
  • 3
  • 20
  • 32