Mar-21-2023, 10:29 PM
(This post was last modified: Mar-22-2023, 06:24 AM by Gribouillis.)
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)
Gribouillis write Mar-22-2023, 06:24 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.