重命名路径中带有空格的文件

2024-05-16 19:02:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件夹叫“真正的侦探”

import shutil
file = "true.detective.s01e04.720p.hdtv.x264-killers.mkv"
dest = "/home/sharefolder/things/Videos/Series/True Detective/"
shutil.copy(file, dest)

上面写着:

^{pr2}$

文件夹“/home/sharefolder/things/Videos/Series/True Detective/”已存在。在

当我设置一个没有空格的文件夹时,一切正常。有什么想法吗?在


Tags: import文件夹truehomevideosfiledestseries
1条回答
网友
1楼 · 发布于 2024-05-16 19:02:43

目标目录必须存在,shutil.copy()才能工作;os.path.isdir(dest)必须是True。如果dest不存在,shutil将尝试将源文件名复制到目录名(包括后面的/),这就是引发异常的原因。在

您可以调用^{}来确保首先正确创建了目标目录:

进口苏蒂尔 导入操作系统

file = "true.detective.s01e04.720p.hdtv.x264-killers.mkv"
dest = "/home/sharefolder/things/Videos/Series/True Detective/"
try:
    os.makedirs(dest)
except OSError:
    # destination directory already exists
    pass
shutil.copy(file, dest)

相关问题 更多 >