目录名中有空格时如何使用copyfile? [英] How to use copyfile when there are spaces in the directory name?

查看:27
本文介绍了目录名中有空格时如何使用copyfile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to perform a simple file copy task under Windows and I am having some problems.

我的第一次尝试是使用

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 找不到源和/或无法创建目标.

copyfile can't find the source and/or can't create the destination.

我的第二个猜测是使用

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

但它又失败了.

有什么提示吗?

编辑

得到的代码是

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

推荐答案

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

I don't think spaces are to blame. You have to escape backslashes in paths, like this:

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

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

or, even better, use the r prefix:

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

这篇关于目录名中有空格时如何使用copyfile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆