相关疑难解决方法(0)

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

我正在使用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 文件吗?

python xml linux file shutil

12
推荐指数
1
解决办法
3万
查看次数

你如何在python中使用数组执行os.path.join?

你如何在python中使用数组执行os.path.join?基本上,我希望能够以数组作为参数运行该命令.任何帮助都非常感谢.

python operating-system join path

9
推荐指数
1
解决办法
4212
查看次数

如何在Python中的文件路径中间插入目录?

我想在给定文件路径的中间插入一个目录名,如下所示:

directory_name = 'new_dir'
file_path0 = 'dir1/dir2/dir3/dir4/file.txt'
file_path1 = some_func(file_path0, directory_name, position=2)
print(file_path1)
>>> 'dir1/dir2/new_dir/dir3/dir4/file.txt'
Run Code Online (Sandbox Code Playgroud)

我查看了 os.path 和 pathlib 包,但看起来它们没有允许在文件路径中间插入的功能。我试过:

import sys,os
from os.path import join

path_ = file_path0.split(os.sep)
path_.insert(2, 'new_dir')
print(join(path_))
Run Code Online (Sandbox Code Playgroud)

但这会导致错误

“需要 str、bytes 或 os.PathLike 对象,而不是列表”

有谁知道允许在文件路径中间插入这样的标准Python函数?或者 - 我怎样才能转向path_可以处理的东西os.path。我是 pathlib 的新手,所以也许我错过了一些东西


编辑:根据问题的答案,我可以建议以下解决方案:

1.)正如 Zach Favakeh 所建议的和这个答案join(*path_)中所写的那样,只需使用“splat”运算符将上面的代码更正即可*,一切都解决了。

2.)按照buran的建议,您可以使用该pathlib软件包,简而言之,它会导致:

from pathlib import PurePath

path_list = list(PurePath(file_path0).parts)
path_list.insert(2, 'new_dir')
file_path1 = PurePath('').joinpath(*path_list)

print(file_path1)
>>> 'dir1/dir2/new_dir/dir3/dir4/file.txt'
Run Code Online (Sandbox Code Playgroud)

python path filepath os.path

6
推荐指数
1
解决办法
5831
查看次数

标签 统计

python ×3

path ×2

file ×1

filepath ×1

join ×1

linux ×1

operating-system ×1

os.path ×1

shutil ×1

xml ×1