Mar-21-2023, 10:29 PM
My task: I have a folder containing many folders named after projects. These project folders have various amounts/levels of subfolders. I want to create new folders with the same name as the project folders in another folder. Then I want to copy files with specific names into the correct newly created project folder. After hours and hours of trial and error I just used chat gpt and got what I belive is pretty close but with one problem that I cant solve. The code creates new folders for all subfolder and not just the project folder. I just want 1 level, new project folders and then all files containing the search words.
(I never coded in Python before and im pretty shit at coding overall so I hope I explained my problem sufficiently)
my(chat gpts) code:
(I never coded in Python before and im pretty shit at coding overall so I hope I explained my problem sufficiently)
my(chat gpts) code:
import os import shutil # Define the search keywords search_words = ['Genomförandebeskrivning', 'administrativa föreskrifter', 'AF', 'GB', 'mervärdersbeskrivning'] # Define the input and output directories input_dir = r'C:\Users\erict\OneDrive\Skrivbord\Anbud' output_dir = r'C:\Users\erict\OneDrive\Skrivbord\Kopior' # Walk through the directories and files in the input directory for dirpath, dirnames, filenames in os.walk(input_dir): # Get the corresponding subdirectory path in the output directory rel_dirpath = os.path.relpath(dirpath, input_dir) output_subdir = os.path.join(output_dir, rel_dirpath) os.makedirs(output_subdir, exist_ok=True) # Loop through the files in the current directory for filename in filenames: # Check if the file contains any of the search keywords if any(word in filename for word in search_words): # Copy the file to the output directory input_filepath = os.path.join(dirpath, filename) output_filepath = os.path.join(output_subdir, filename) shutil.copy2(input_filepath, output_filepath)