(unicode错误)“UnicodeScape”编解码器无法解码位置16-17中的字节:已截断\uxxx escap

2024-05-19 01:17:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我要导入pyusb库的一个模块,该模块位于d:\ pyusb-1.0.0a2\usb中。因此,首先我必须将其路径添加到sys.path。但我收到了下面的错误。

注意:我可以成功导入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

Tags: 模块path路径ontype错误sysbit
2条回答

你需要使用原始字符串

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

或是避开反睫毛

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

或使用正斜杠

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

否则,Python将尝试将\usb解释为Unicode转义序列(如\uBEEF),该转义序列由于明显的原因而失败。

在flask中添加文件上传方法时,我得到了syntaxError,如下所示


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

控制台显示错误如下:


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

所以,我认为这是由Unicode转义序列中的'\u'引起的,我们应该使用原始字符串来修复它。


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

相关问题 更多 >

    热门问题