使用shutil移动文件时出错

Pad*_*ham 1 python file dir shutil

我正在尝试创建一个简单的函数,该函数查找以某个字符串开头的文件,然后将它们移动到一个新目录,但我不断收到以下类型的错误:shutil "IOError: [Errno 2] No such file or directory: ' 18-1.pdf'",即使文件存在。

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)
Run Code Online (Sandbox Code Playgroud)

我是否错误地使用了 Shutil?

正确的代码:

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)
Run Code Online (Sandbox Code Playgroud)

ayc*_*dee 5

看起来您没有提供shutil.move. 尝试:

if _file.startswith(start):
    shutil.move(os.path.abspath(_file), new_dir)
Run Code Online (Sandbox Code Playgroud)

如果失败,请尝试打印_file,并new_dir连同结果一起os.getcwd()添加到您的答案中。