import os from datetime import datetime def merge_files(file_paths): # Dictionary to hold file contents by extension files_by_extension = {} # Read each file and group contents by extension for file_path in file_paths: _, ext = os.path.splitext(file_path) if ext not in files_by_extension: files_by_extension[ext] = [] with open(file_path, 'r') as file: files_by_extension[ext].append(file.read()) # Ensure the .old directory exists old_dir = '.old' if not os.path.exists(old_dir): os.makedirs(old_dir) # Write merged contents to new files for ext, contents in files_by_extension.items(): current_date = datetime.now().strftime("%Y-%m-%d") merged_file_path = f'{current_date}{ext}' # Move existing merged file to .old directory if os.path.exists(merged_file_path): os.rename(merged_file_path, os.path.join(old_dir, f'{current_date}{ext}')) with open(merged_file_path, 'w') as merged_file: for content in contents: merged_file.write(content) if __name__ == "__main__": # Example usage: specify the file paths you want to merge file_paths = [ '/test/first.csv', '/test/second.csv', '/test/third.csv' ] merge_files(file_paths)