File size: 1,240 Bytes
32e4bc9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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.") |