Reputation: 1
I am a beginner on Python. I would like to copy specific files (using pattern matching and shutil.copy) from directory and sub directories (using os.walk) into a new directory. The code works only for one file from one sub directory but not with multiple sub directories.
One specific file in only one sub directory can be copied into a new directory by using pattern matching and shutil.copy. When I want to match specific files from different sub directories it's not possible to copy into the new directory.
Here the code for the file in one sub directory :
import os
import shutil
import shutil
from fnmatch import fnmatch
root = r'C:\Users\Fabien.Seychelles\Documents\Projects\Python_weather\Weather_Files'
dest =r'C:\Users\Fabien.Seychelles\Documents\Projects\Python_weather\CSV_converted'
pattern2 = '*TMY*.epw'
for path, subdirs, files in os.walk(root):
for filename in files:
if fnmatch(filename, pattern2):
shutil.copy(root + '\\'+ filename, dest)
I was thinking about using a recursive copy, or shutil.copytree but I am not really sure.
Thank you
Upvotes: 0
Views: 487
Reputation: 3682
I'm guessing you're on windows?
You could call the "dir" command programmatically using subprocess or os.system and consume the output. The flags you could use are
dir /s /b
/s for sub-directories and /b for bare output
Upvotes: 0