0

I'm trying to copy images to a local directory for my program to use later on.

this is the syntax i have:

import shutil
import os
path = 'C:\t1\x.txt' 
source = os.listdir(path)
destination = "C:\t2" #pre-existing folder
for files in source:
    if files.endswith(".txt"):
        shutil.copy(files,destination)

The error i get says:

(unicode error) 'unicodescape' codec cant decode bytes in position 5-6: truncated \xXX escape.

1 Answer 1

0

You need to do one of the following:

path = r'C:\t1\x.txt'

or

path = 'C:\\t1\\x.txt'

or as Bakuriu pointed out

path = 'C:/t1/x.txt'

And the same for destination

The issue is that the \ character causes Python to interpret the string differently. So you can either tell it to treat the string as raw text (r'') or give it the \ literal, which is \\

Alternatively, you could make your script platform independent by using os.path.join() to construct folder paths. This will always construct them with the correct delimeters for whatever platform you're running on. Be aware of this from the docs:

Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

2
  • Note that Windows path can use / instead of \ as a directory separator. You can use: C:/t1/x.txt for example. All the APIs can use both separators (with the exception of the paths that begin with \\?. Some applications may fail to handle them as separators, but since python provides access to the API there isn't any problem with / in the paths).
    – Bakuriu
    Jan 23, 2014 at 19:36
  • @Bakuriu thanks for that, I've updated the answer to include it
    – wnnmaw
    Jan 23, 2014 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.