Errno 2 using python shutil.py 文件目的地没有这样的文件或目录

OMG*_*gar 12 python xml linux file shutil

我正在使用shutil python 模块在linux redhat 机器上复制文件和目录。

我编写了以下方法,它接受 2 个参数:src(正在收集的文件或目录的路径)和目标(将收集的日志/目录粘贴到的所需新路径)。

def copy(src, destination):
    if(os.path.exists(src)):
        if(os.path.isdir(src)):
            if(os.path.exists(destination)):
                shutil.copytree(src, destination+getTimeStamp())
            else:
                shutil.copytree(src, destination)
        else:
            shutil.copy(src, destination)
    else:
        print src+" not found"
Run Code Online (Sandbox Code Playgroud)

我一直在用这个方法很好,但我最近在运行这段代码时遇到了一个错误:

copy("/home/midgar/logs/logger.xml", currentPath+"/testrun/logs/logger.xml")
Run Code Online (Sandbox Code Playgroud)

错误:IOError: [Errno 2] No such file or directory: 'collectedLogs/testrun/logs/logger.xml'

如果它正在寻找的文件或目录是 src,我会理解这个错误意味着什么,但这是导致错误的目标。我发现这行抛出错误的代码行在我的复制方法中:“shutil.copy(src, destination)”。

到目前为止,我的复制方法只是覆盖现有文件,如果存在现有目录,它会创建一个带有时间戳的新目录。在这种情况下,目标文件无论如何都不存在。那么,这可能是什么问题?为什么我会在 DESTINATION 路径中出现此错误(当我通常希望在 SRC 路径中看到此类错误时)。

可能是因为这是一个 .xml 文件吗?

Eri*_*och 9

当我收到此错误时,通常意味着其中一个文件夹不存在。

我写了一个简单的脚本来测试这个。在下面的脚本中,备份文件夹确实存在,但今天文件夹不存在。当我运行脚本时,我得到和你一样的错误。

IOError: [Errno 2] 没有这样的文件或目录:'backup/today/my_file.txt'

import shutil
shutil.copy("my_file.txt", "backup/today/my_file.txt")
Run Code Online (Sandbox Code Playgroud)

如果您的所有文件夹都存在,我会检查以确保它们的权限没有改变。