0

I want to copy all files from a directory to a new folder. But there are multiple files in subfolders and i just want to copy all files with "NFL_V2" in it.

I am using python and tried this with os and shutil.

Dont know how to look for files with these letters and als if .find is the correct way-

Thanks!


UPDATE I could solve this issue by using glob.glob()

Find the fixed code below!

source_dir = r"C:\folders\SHP_20211001"
dest_dir = r"C:\folders\DKM_NFL"

keyword = "NFL_V2"

for fname in glob.glob(source_dir+"/**", recursive=True):
    if keyword in fname:
        shutil.copy(fname, dest_dir)
        print("Copied " + fname + " to new folder")
Saelon
  • 1
  • 1
  • This might help: https://stackoverflow.com/questions/2186525/how-to-use-glob-to-find-files-recursively – JonSG Feb 21 '23 at 15:34
  • Since i cannot edit my post, here`s my updated code: keyword = r"*\*NFL_V2*.*" for fname in os.listdir(source_dir): if keyword in fname: shutil.copy(fname, dest_dir) print(fname) – Saelon Feb 21 '23 at 15:39
  • yes, rather than `os.listdir()` try `pathlib.Path.rglob()` – JonSG Feb 21 '23 at 15:41
  • i splitted my script in single parts. the copy function is working. So i think there is a problem with search function for the wanted files – Saelon Feb 21 '23 at 16:23
  • can you update your code with your current attempt using `pathlib.Path.rglob()`? – JonSG Feb 21 '23 at 16:25
  • Does this answer your question? [Get a filtered list of files in a directory](https://stackoverflow.com/questions/2225564/get-a-filtered-list-of-files-in-a-directory) – Abdul Aziz Barkat Feb 22 '23 at 13:55

0 Answers0