Created
March 3, 2024 21:10
-
-
Save wyattowalsh/268f956053b18e71e868a233fab70a57 to your computer and use it in GitHub Desktop.
Python3 to Merge .txt Files in a Directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
def merge_txt_files(input_dir, output_file): | |
""" | |
Merges all .txt files found in the specified input directory into a single output file. | |
Parameters: | |
- input_dir (str): The directory to search for .txt files. | |
- output_file (str): The path to the output file where the merged content will be stored. | |
Returns: | |
- None | |
""" | |
try: | |
# Ensure the input directory exists | |
if not os.path.isdir(input_dir): | |
print(f"The specified input directory does not exist: {input_dir}") | |
return | |
# Find all .txt files in the input directory | |
txt_files = [os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.txt')] | |
# Sort files alphabetically to ensure predictable order | |
txt_files.sort() | |
# Merge files | |
with open(output_file, 'w') as outfile: | |
for file in txt_files: | |
with open(file, 'r') as infile: | |
outfile.write(infile.read() + '\n') # Add a newline between files for clarity | |
print(f"All .txt files have been merged into {output_file}") | |
except Exception as e: | |
print(f"An error occurred: {e}") | |
if __name__ == "__main__": | |
if len(sys.argv) != 3: | |
print("Usage: python merge_txt_files.py <input_directory> <output_file>") | |
sys.exit(1) | |
input_dir, output_file = sys.argv[1], sys.argv[2] | |
merge_txt_files(input_dir, output_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment