当目录名中有空格时如何使用copyfile?

Ste*_*roz 5 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)
Run Code Online (Sandbox Code Playgroud)

copyfile 无法找到源和/或无法创建目的地.

我的第二个猜测是使用

shutil.copyfile('"' + source + '"', '"' + destination + '"')
Run Code Online (Sandbox Code Playgroud)

但它又失败了.

任何提示?


编辑

结果代码是

IOError: [Errno 22] Invalid argument: '"C:\Documents and Settings\Some directory\My file.txt"'
Run Code Online (Sandbox Code Playgroud)

Dzi*_*inX 11

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

source = 'C:\\Documents and Settings\\Some directory\\My file.txt'
Run Code Online (Sandbox Code Playgroud)

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

source = r'C:\Documents and Settings\Some directory\My file.txt'
Run Code Online (Sandbox Code Playgroud)