preveen-stack / test

0 stars 0 forks source link

Concat all .txt files recursively #13

Open preveen-stack opened 1 year ago

preveen-stack commented 1 year ago

Sure! Here's an example of a script in Python that recursively reads all text files in a directory and concatenates their contents into a single file:

import os

def concatenate_files(directory, output_file):
    with open(output_file, 'w') as outfile:
        for root, _, files in os.walk(directory):
            for file in files:
                if file.endswith('.txt'):
                    file_path = os.path.join(root, file)
                    with open(file_path, 'r') as infile:
                        outfile.write(infile.read())

    print(f'Successfully concatenated files into {output_file}!')

# Example usage
directory = '/path/to/directory'  # Directory containing text files
output_file = 'concatenated_files.txt'  # Output file name
concatenate_files(directory, output_file)

This script uses the os module in Python to walk through the directory recursively, identifying all text files by their .txt extension. It then opens each text file, reads its contents, and writes them into the output file. The output file will be created in the same directory as the script, and it will contain the concatenated text of all the text files found in the specified directory.