python - 使用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 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)

如果失败,请尝试打印 _filenew_dir 以及 os.getcwd() 的结果,并将它们添加到您的答案中。

关于python - 使用shutil移动文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22230043/

相关文章:

python - 调试 py2exe 创建的 library.zip,无需访问原始源

c - 需要一种快速的方法将大块数据写入 C 文件

python读取文件,根据条件抓取行

windows - cmd.exe 中区分大小写的目录

PHP basename( __DIR__ ) 在某些服务器上返回 _DIR_

python - 我怎样才能让 tormysql 做插入?

Python 脚本无法在 Windows 上运行(但可以在 Mac 上运行)

python - 如何在 OSX 10.6 中将 MySQLdb 与 Python 和 Django 一起使用?

Python:从 CSV 文件的每一行中提取第一个元素

java - Android - 使用扫描仪读取文件,如何获取文件