SheridanCoriana6

subtitle join.py

Mar 28th, 2026
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | Software | 0 0
  1. import os
  2. from tkinter import Tk, filedialog
  3. import re
  4.  
  5. def get_directory():
  6.     """Displays a dialog to select directory with part files."""
  7.     root = Tk()
  8.     root.withdraw()
  9.     directory = filedialog.askdirectory(
  10.         title="Select Directory with Part Files"
  11.     )
  12.     return directory
  13.  
  14. def merge_files(directory):
  15.     try:
  16.         # Get all files in directory
  17.         all_files = os.listdir(directory)
  18.        
  19.         # Filter files ending with 'partX' where X is a number
  20.         part_files = [f for f in all_files if re.match(r'.+_part\d+\.txt$', f)]
  21.        
  22.         if not part_files:
  23.             print("No part files found in the selected directory.")
  24.             return
  25.        
  26.         # Sort files by part number
  27.         part_files.sort(key=lambda x: int(re.search(r'_part(\d+)\.txt$', x).group(1)))
  28.        
  29.         # Get base name from first file (remove _partX.txt)
  30.         base_name = re.sub(r'_part\d+\.txt$', '.txt', part_files[0])
  31.        
  32.         # Create output file path
  33.         output_path = os.path.join(directory, base_name)
  34.        
  35.         # Merge all parts
  36.         with open(output_path, 'w', encoding='utf-8') as outfile:
  37.             for part_file in part_files:
  38.                 file_path = os.path.join(directory, part_file)
  39.                 with open(file_path, 'r', encoding='utf-8') as infile:
  40.                     content = infile.read()
  41.                     outfile.write(content)
  42.        
  43.         print(f"Files successfully merged into: {base_name}")
  44.         print(f"Merged {len(part_files)} parts.")
  45.        
  46.     except Exception as e:
  47.         print(f"An error occurred: {e}")
  48.  
  49. if __name__ == "__main__":
  50.     directory = get_directory()
  51.     if directory:
  52.         merge_files(directory)
  53.     else:
  54.         print("No directory selected. Exiting.")
Advertisement
Add Comment
Please, Sign In to add comment