How to use copy file if there are spaces in the directory name?

I am trying to perform a simple task of copying files 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 cannot find the source and / or cannot create the destination.

My second assumption was to use

 shutil.copyfile('"' + source + '"', '"' + destination + '"') 

But it does not work again.

Any clues?


Edit

Received code

 IOError: [Errno 22] Invalid argument: '"C:\Documents and Settings\Some directory\My file.txt"' 
+4
source share
3 answers

I don’t think the gaps are to blame. You should avoid backslashes in paths, for example:

 source = 'C:\\Documents and Settings\\Some directory\\My file.txt' 

or better yet, use the r prefix:

 source = r'C:\Documents and Settings\Some directory\My file.txt' 
+10
source

Copyfile handles space'd file names.

You do not escape \ in the file path 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 this, try the following:

 print 'Incorrect: C:\Test\Derp.txt' print 'Correct : C:\\Test\\Derp.txt' 

There seem to be other problems. Errno 22 indicates another problem. I saw this error in the following scenarios:

  • The source file or target file is being used by another process.
  • The file path contains trendy Unicode characters.
  • Other access problems.
+3
source

Use slashes or the string r'raw '.

+3
source

Source: https://habr.com/ru/post/1399023/


All Articles