Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用shutil移动文件时出错_Python_File_Dir_Shutil - Fatal编程技术网

Python 使用shutil移动文件时出错

Python 使用shutil移动文件时出错,python,file,dir,shutil,Python,File,Dir,Shutil,我试图创建一个简单的函数,查找以某个字符串开头的文件,然后将其移动到新目录,但我不断从shutil“IOError:[Errno 2]没有这样的文件或目录:'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

我试图创建一个简单的函数,查找以某个字符串开头的文件,然后将其移动到新目录,但我不断从shutil“IOError:[Errno 2]没有这样的文件或目录:'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)
我使用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)

看起来您没有给出shutil.move的完整路径。尝试:

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

如果失败,请尝试打印
\u文件
,以及
新目录
以及
os.getcwd()
的结果,并将它们添加到您的答案中

看起来您没有给出shutil.move的完整路径。尝试:

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

如果失败,请尝试打印
\u文件
,以及
新目录
以及
os.getcwd()
的结果,并将它们添加到您的答案中

谢谢,完全忽略了我只给出文件名而不是完整路径的事实。谢谢,完全忽略了我只给出文件名而不是完整路径的事实。