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"'
SteeveDroz
  • 6,006
  • 6
  • 33
  • 65

3 Answers3

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'
Dzinx
  • 55,586
  • 10
  • 60
  • 78
  • 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`? – SteeveDroz Feb 29 '12 at 14:25
  • 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. – Dzinx Feb 29 '12 at 14:33
  • `print repr(source)` returns double-backslash'd paths. – SteeveDroz Feb 29 '12 at 14:36
4

Use forward slashes or a r'raw string'.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
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.
Deestan
  • 16,738
  • 4
  • 32
  • 48
  • 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. – Ignacio Vazquez-Abrams Feb 29 '12 at 14:23
  • 1
    @IgnacioVazquez-Abrams Correct. But I suspect he is sanitizing/anonymizing the paths in the code examples, so it is still worth considering. – Deestan Feb 29 '12 at 14:29