Last active
April 11, 2023 16:13
-
-
Save Shubhang/dec7538d5d4bf4736f8fedc599bca2a5 to your computer and use it in GitHub Desktop.
group by using hyphens, underscores and numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import shutil | |
import re | |
def main(): | |
base_dir = '.' # Set the base directory to search for files | |
for root, _, files in os.walk(base_dir): | |
for file in files: | |
new_folder_name = None | |
if '-' in file: | |
# Extract the folder name based on the text before the "-" character | |
new_folder_name = file.split(' -')[0].strip() | |
else: | |
# Extract the folder name based on the text before the first numerical character | |
match = re.search(r'\d', file) | |
if match: | |
index = match.start() | |
new_folder_name = file[:index].strip() | |
if new_folder_name: | |
# Append "_folder" to the folder name to avoid naming conflicts | |
new_folder_name += "_folder" | |
# Create the folder in the base directory if it doesn't exist | |
new_folder_path = os.path.join(base_dir, new_folder_name) | |
if not os.path.exists(new_folder_path): | |
os.makedirs(new_folder_path) | |
# Move the file into the new folder in the base directory | |
file_path = os.path.join(root, file) | |
new_file_path = os.path.join(new_folder_path, file) | |
shutil.move(file_path, new_file_path) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment