How to use copyfile when there are spaces in the directory name?

烈酒焚心 提交于 2019-11-29 21:54:16

问题


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

My first attempt was to use

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 can't find the source and/or can't create the destination.

My second guess was to use

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

But it's failing again.

Any hint?


Edit

The resulting code is

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

回答1:


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'

or, even better, use the r prefix:

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



回答2:


Use forward slashes or a r'raw string'.




回答3:


Copyfile handles space'd filenames.

You are not escaping the \ in the file paths correctly.

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)

To illustrate, try running this:

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

It seems there are other issues as well. Errno 22 indicates another problem. I've seen this error in the following scenarios:

  • Source file or target file is in use by another process.
  • File path contains fancy Unicode characters.
  • Other access problems.


来源:https://stackoverflow.com/questions/9500735/how-to-use-copyfile-when-there-are-spaces-in-the-directory-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!