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