Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"'
like image 601
SteeveDroz Avatar asked Feb 29 '12 14:02

SteeveDroz


People also ask

How do I copy a file with spaces?

Use quotation marks when specifying long filenames or paths with spaces. For example, typing the copy c:\my file name d:\my new file name command at the command prompt results in the following error message: The system cannot find the file specified. The quotation marks must be used.


1 Answers

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'
like image 165
DzinX Avatar answered Sep 17 '22 15:09

DzinX