Naphula commited on
Commit
ca5eaa5
·
verified ·
1 Parent(s): bd4dc44

Upload folder_content_combiner_anyfiles.py

Browse files
Files changed (1) hide show
  1. folder_content_combiner_anyfiles.py +104 -0
folder_content_combiner_anyfiles.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ # --- Configuration ---
5
+ OUTPUT_FILENAME = "!combo.txt"
6
+ # ALLOWED_EXTENSIONS = (".py", ".md", ".env", ".bat") # Removed this line
7
+ # --- End Configuration ---
8
+
9
+ def combine_files_in_current_folder():
10
+ """
11
+ Combines *all files* in the script's current directory
12
+ (and its subdirectories) into a single output file, sorted alphabetically
13
+ by filename, with separator tags and overall ``` wrapping.
14
+ Excludes the script itself and the output file.
15
+ """
16
+ try:
17
+ # Determine the script's own path and name
18
+ if getattr(sys, 'frozen', False):
19
+ # If running as a bundled executable (e.g., PyInstaller)
20
+ script_full_path = os.path.abspath(sys.executable)
21
+ else:
22
+ # If running as a .py script
23
+ script_full_path = os.path.abspath(__file__)
24
+
25
+ script_dir = os.path.dirname(script_full_path)
26
+ script_basename = os.path.basename(script_full_path)
27
+ output_filepath = os.path.join(script_dir, OUTPUT_FILENAME)
28
+
29
+ print(f"Running in: {script_dir}")
30
+ print(f"Excluding self: {script_basename}")
31
+ print(f"Output will be: {output_filepath}")
32
+ print("-" * 30)
33
+
34
+ file_paths_to_process = []
35
+
36
+ # Walk through the directory tree starting from the script's directory
37
+ for root, _, files in os.walk(script_dir):
38
+ for filename in files:
39
+ # Construct full path to compare with script_full_path
40
+ current_file_full_path = os.path.join(root, filename)
41
+
42
+ # 1. Exclude the script itself
43
+ # 2. Exclude the output file if it already exists and is being processed
44
+ if (os.path.normpath(current_file_full_path) == os.path.normpath(script_full_path) or
45
+ filename == OUTPUT_FILENAME):
46
+ continue
47
+
48
+ # Removed the ALLOWED_EXTENSIONS check. All files (not excluded above) will be added.
49
+ file_paths_to_process.append((filename, current_file_full_path))
50
+
51
+ # Sort files alphabetically by their base filename
52
+ file_paths_to_process.sort(key=lambda x: x[0])
53
+
54
+ if not file_paths_to_process:
55
+ print(f"No files found (other than this script or the output file).")
56
+ # Create an empty combo file
57
+ with open(output_filepath, 'w', encoding='utf-8') as outfile:
58
+ outfile.write("```\n```\n")
59
+ print(f"Empty '{output_filepath}' created.")
60
+ return
61
+
62
+ print(f"\nFound {len(file_paths_to_process)} files to combine:")
63
+ for basename, _ in file_paths_to_process:
64
+ print(f" - {basename}")
65
+ print("-" * 30)
66
+
67
+ with open(output_filepath, 'w', encoding='utf-8') as outfile:
68
+ outfile.write("```\n") # Start with ```
69
+
70
+ for basename, full_path in file_paths_to_process:
71
+ relative_path = os.path.relpath(full_path, script_dir)
72
+ print(f"Processing: {basename} (from {relative_path})")
73
+ try:
74
+ # Attempt to read as text. For binary files, this might produce
75
+ # garbled output or raise an error if not for errors='replace'.
76
+ # errors='replace' will insert a replacement character for undecodable bytes.
77
+ with open(full_path, 'r', encoding='utf-8', errors='replace') as infile:
78
+ content = infile.read()
79
+ # Use relative path in the tag for clarity if files have same name in different subdirs
80
+ outfile.write(f"<{relative_path}>\n")
81
+ outfile.write(content)
82
+ outfile.write(f"\n</{relative_path}>\n\n") # Add extra newline for readability
83
+ except Exception as e:
84
+ print(f" Error reading file {full_path}: {e}")
85
+ outfile.write(f"<{relative_path}>\n")
86
+ outfile.write(f"Error reading file: {e}\nContent might be incomplete or missing.\n")
87
+ outfile.write(f"</{relative_path}>\n\n")
88
+
89
+ outfile.write("```\n") # End with ```
90
+ print(f"\nSuccessfully combined files into '{output_filepath}'")
91
+
92
+ except Exception as e:
93
+ print(f"An unexpected error occurred: {e}")
94
+ import traceback
95
+ traceback.print_exc()
96
+
97
+ if __name__ == "__main__":
98
+ combine_files_in_current_folder()
99
+ # Keep the console window open until the user presses Enter
100
+ # This is helpful when double-clicking the script on Windows.
101
+ try:
102
+ input("\nPress Enter to exit...")
103
+ except EOFError: # Happens if stdin is not available (e.g. some CI environments)
104
+ pass