Python move files from directories that match given criteria to new directory

房东的猫 提交于 2019-12-02 09:48:05

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)

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!