【问题标题】:How to use copyfile when there are spaces in the directory name?目录名中有空格时如何使用copyfile?
【发布时间】:2012-03-19 00:49:16
【问题描述】:

我正在尝试在 Windows 下执行简单的文件复制任务,但遇到了一些问题。

我的第一次尝试是使用

import shutils

source = 'C:\Documents and Settings\Some directory\My file.txt'
destination = 'C:\Documents and Settings\Some other directory\Copy.txt'

shutil.copyfile(source, destination)

copyfile 找不到源和/或无法创建目标。

我的第二个猜测是使用

shutil.copyfile('"' + source + '"', '"' + destination + '"')

但它又失败了。

有什么提示吗?


编辑

生成的代码是

IOError: [Errno 22] Invalid argument: '"C:\Documents and Settings\Some directory\My file.txt"'

【问题讨论】:

  • 对我来说似乎并不明显。也许你应该证明这一点。
  • 考虑在内。我删除了那个无用的词。
  • 不要只删除这个词,删除所有你的假设。没有理由仅仅因为空格而失败。

标签: python windows file-copying


【解决方案1】:

我不认为空间是罪魁祸首。您必须在路径中转义反斜杠,如下所示:

source = 'C:\\Documents and Settings\\Some directory\\My file.txt'

或者,更好的是,使用r 前缀:

source = r'C:\Documents and Settings\Some directory\My file.txt'

【讨论】:

  • 这可能行得通。不过,我没有定义路径,我有一个浏览文件夹并返回文件名的脚本。 source 在其他地方定义。我怎样才能r source
  • 好吧,你应该在它定义的地方转义它。如果它不在代码中,那么它可能不需要转义。做一个print repr(source) 以确保。反斜杠应该被转义。
  • print repr(source) 返回双反斜杠路径。
【解决方案2】:

使用正斜杠或 r'raw string'。

【讨论】:

    【解决方案3】:

    Copyfile 处理带有空格的文件名。

    您没有正确转义文件路径中的 \。

    import shutils
    
    source = 'C:\\Documents and Settings\\Some directory\\My file.txt'
    destination = 'C:\\Documents and Settings\\Some other directory\\Copy.txt'
    
    shutil.copyfile(source, destination)
    

    为了说明,尝试运行这个:

    print 'Incorrect: C:\Test\Derp.txt'
    print 'Correct  : C:\\Test\\Derp.txt'
    

    似乎还有其他问题。 Errno 22 表示另一个问题。我在以下场景中看到了这个错误:

    • 源文件或目标文件正在被另一个进程使用。
    • 文件路径包含花哨的 Unicode 字符。
    • 其他访问问题。

    【讨论】:

    • 虽然这是真的并且反斜杠应该被转义,但它们都不是有效的,因此正常情况下会导致反斜杠后跟字符,因此不应导致错误在这种情况下。
    • @IgnacioVazquez-Abrams 正确。但我怀疑他正在清理/匿名代码示例中的路径,所以仍然值得考虑。
    猜你喜欢
    • 2019-06-07
    • 2013-02-08
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2016-02-27
    • 2013-08-21
    相关资源
    最近更新 更多