error moving file with shutil

北战南征 提交于 2019-12-08 10:21:39

问题


I am trying to create a simple function that finds files that begin with a certain string and then move them to a new directory but I keep getting the following kinds of errors from shutil "IOError: [Errno 2] No such file or directory: '18-1.pdf'", even though the file exists.

import os
import shutil
def mv_files(current_dir,start):
    # start of file name
    start = str(start)
    # new directory ro move files in to
    new_dir = current_dir + "/chap_"+ start
    for _file in os.listdir(current_dir):
        # if directory does not exist, create it
        if not os.path.exists(new_dir):
                os.mkdir(new_dir)
        # find files beginning with start and move them to new dir
        if _file.startswith(start):
            shutil.move(_file, new_dir)

Am I using shutil incorrectly?

correct code:

import os
import shutil
def mv_files(current_dir,start):
    # start of file name
    start = str(start)
    # new directory ro move files in to
    new_dir = current_dir + "/chap_" + start
    for _file in os.listdir(current_dir):
        # if directory does not exist, create it
        if not os.path.exists(new_dir):
            os.mkdir(new_dir)
       # find files beginning with start and move them to new dir
        if _file.startswith(start):
            shutil.move(current_dir+"/"+_file, new_dir)

回答1:


It looks like you aren't giving the full path to shutil.move. Try:

if _file.startswith(start):
    shutil.move(os.path.abspath(_file), new_dir)

If that fails, try printing _file, and new_dir along with the result of os.getcwd() and adding them to your answer.



来源:https://stackoverflow.com/questions/22230043/error-moving-file-with-shutil

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