python - 目录名有空格时如何使用copyfile?

标签 python windows file-copying

我正在尝试在 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"'

最佳答案

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

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

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

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

关于python - 目录名有空格时如何使用copyfile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9500735/

相关文章:

windows - 从 Visual Studio 2017 连接到适用于 Linux 的 Windows 子系统

python - 检查 shutil.copyfile 何时完成

c# - 为什么 CopyFileEx 的 FileUtilities.CopyFile 包装器会干扰 winforms?

python - 如何使用外部文件的答案进行测验?

python - 通过 REST 将 Swift 数据发送到服务器并执行 Python 代码

windows - 什么时候使用\\.\c : and when to use c:?

Python SQL - 两个左连接

Python 3.3 - 生成奇数

windows - 将命令提示符的输出放入剪贴板