Python Move Files From Directories That Match Given Criteria To New Directory
I have a directory that looks something like this: . ├── files.py ├── homework ├── hw1 │ └── hw1.pdf ├── hw10 │ └── hw10.pdf ├─�
Solution 1:
try this:
from os import walk, path
source='/home/kalenpw/Documents/School/2017Spring/CS3385/homework/'for (dirpath, dirnames, filenames) in walk(source):
for file in filenames:
shutil.move(path.join(dirpath,file), source)
Solution 2:
You're almost there. When you get to shutil.move(eachFile, source), 'eachFile' here is only the name of the file you want. For example, 'hw13.pdf'. So it will try to search for it in the root path, but there is no 'hw13.pdf' in the root (as the Exception message points out).
What you need to do is just join the name of the folder you're in to the name of the file you want to move:
for f in files:
if f.startswith("hw") and len(f) > 2:
for eachFile in os.listdir(f):
filePath = os.path.join(f, eachFile)
shutil.move(filePath, source)
Post a Comment for "Python Move Files From Directories That Match Given Criteria To New Directory"