Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from tkinter import Tk, filedialog
- import re
- def get_directory():
- """Displays a dialog to select directory with part files."""
- root = Tk()
- root.withdraw()
- directory = filedialog.askdirectory(
- title="Select Directory with Part Files"
- )
- return directory
- def merge_files(directory):
- try:
- # Get all files in directory
- all_files = os.listdir(directory)
- # Filter files ending with 'partX' where X is a number
- part_files = [f for f in all_files if re.match(r'.+_part\d+\.txt$', f)]
- if not part_files:
- print("No part files found in the selected directory.")
- return
- # Sort files by part number
- part_files.sort(key=lambda x: int(re.search(r'_part(\d+)\.txt$', x).group(1)))
- # Get base name from first file (remove _partX.txt)
- base_name = re.sub(r'_part\d+\.txt$', '.txt', part_files[0])
- # Create output file path
- output_path = os.path.join(directory, base_name)
- # Merge all parts
- with open(output_path, 'w', encoding='utf-8') as outfile:
- for part_file in part_files:
- file_path = os.path.join(directory, part_file)
- with open(file_path, 'r', encoding='utf-8') as infile:
- content = infile.read()
- outfile.write(content)
- print(f"Files successfully merged into: {base_name}")
- print(f"Merged {len(part_files)} parts.")
- except Exception as e:
- print(f"An error occurred: {e}")
- if __name__ == "__main__":
- directory = get_directory()
- if directory:
- merge_files(directory)
- else:
- print("No directory selected. Exiting.")
Advertisement
Add Comment
Please, Sign In to add comment