TheGoodUser
TheGoodUser

Reputation: 1198

(unicode error) 'unicodeescape' codec can't decode bytes in position 16-17: truncated \uXXXX escape

I want to import one module of pyusb library that is in the d:\pyusb-1.0.0a2\usb. So first of all I must add its path to sys.path. But I receive the below error.

Note : I successfully can import d:\pyusb-1.0.0a2 !!!

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import sys
>>> sys.path.append('d:\pyusb-1.0.0a2\usb')
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 16-17: truncated \uXXXX escape

Upvotes: 3

Views: 13383

Answers (2)

gotouei
gotouei

Reputation: 1

I got the syntaxError when add the file upload method in flask as follows,


    def upload():
         if request.method == 'POST':
             f = request.files['file']
             basepath = os.path.dirname(__file__)
             print(basepath)
             upload_path = os.path.join(basepath, 'static\files',secure_filename(f.filename))
             f.save(upload_path)
             return redirect(url_for('upload'))
         return render_template('upload.html')

The console shows error as follows:


upload_path = os.path.join(basepath,r'static\files',secure_filename(f.filename))

So,I think it caused by '\u' in Unicode Escape Sequence,we should use raw strings to fix it.


upload_path = os.path.join(basepath,r'static\files',secure_filename(f.filename))

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336208

You need to use a raw string

>>> sys.path.append(r'd:\pyusb-1.0.0a2\usb')

or escape the backslashes

>>> sys.path.append('d:\\pyusb-1.0.0a2\\usb')

or use forward slashes

>>> sys.path.append('d:/pyusb-1.0.0a2/usb')

Otherwise, Python will try to interpret \usb as a Unicode escape sequence (like \uBEEF) which fails for obvious reasons.

Upvotes: 13

Related Questions