import os import shutil def flatten_directory(path): """ Flattens the directory structure by moving files from subdirectories to the parent directory. """ print(f"Flattening files in: {path}") if not os.path.isdir(path): print(f"Error: Directory not found at {path}") return # Walk through the directory for dirpath, dirnames, filenames in os.walk(path): # Don't process the root directory itself in the first iteration if dirpath == path: continue for filename in filenames: # Construct full old and new paths old_file_path = os.path.join(dirpath, filename) new_file_path = os.path.join(path, filename) # Move the file to the parent directory shutil.move(old_file_path, new_file_path) print(f"Moved: {old_file_path} -> {new_file_path}") # After moving all files, if the subdirectory is empty, remove it if not os.listdir(dirpath): os.rmdir(dirpath) print(f"Removed empty directory: {dirpath}") if __name__ == "__main__": flatten_directory('train') flatten_directory('test') print("File flattening complete.")