How to use copyfile when there are spaces in the d

2019-02-10 13:24发布

问题:

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.