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

SteeveDroz picture SteeveDroz · Feb 29, 2012 · Viewed 18.2k times · Source

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"'

Answer

DzinX picture DzinX · Feb 29, 2012

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'