重命名路径中包含空格的文件

时间:2014-03-16 10:17:01

标签: python

我有一个名为" True Detective"

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

它说:

IOError: [Errno 21] Is a directory: '/home/sharefolder/things/Videos/Series/True Detective/'

文件夹" / home / sharefolder / things / Videos / Series / True Detective /"存在。

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

1 个答案:

答案 0 :(得分:0)

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

您可以调用os.makedirs()以确保首先正确创建目标目录:

导入shutil    import os

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)
相关问题