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

3

8

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"'
Anastigmat answered 29/2, 2012 at 14:18 Comment(3)
Doesn't seem obvious to me. Maybe you should prove it.Protectionism
Taken into account. I removed that useless word.Anastigmat
Don't just remove the word, remove all your assumptions. There is no reason for it to be failing just because of a space.Protectionism
R
15

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'
Roque answered 29/2, 2012 at 14:22 Comment(3)
That may work. I'm not defining the path, though, I have a scrit that browses a folder and returns the file names. source is defined somewhere else. How can I r source?Anastigmat
Well, you should escape it where it's defined. If it's not in the code, then it probably doesn't need to be escaped. Do a print repr(source) to make sure. The backslashes should be escaped then.Roque
print repr(source) returns double-backslash'd paths.Anastigmat
R
4

Use forward slashes or a r'raw string'.

Resolved answered 29/2, 2012 at 14:23 Comment(0)
O
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.
Oswell answered 29/2, 2012 at 14:20 Comment(2)
While this is true and that backslashes should be escaped, none of them are valid and so result in a backslash followed by the character as normal and so should not cause an error in this case.Protectionism
@IgnacioVazquez-Abrams Correct. But I suspect he is sanitizing/anonymizing the paths in the code examples, so it is still worth considering.Oswell

© 2022 - 2024 — McMap. All rights reserved.