在Python 3中导入CSV文件时出现unicodeescape错误

时间:2017-08-17 12:54:25

标签: python python-3.x csv

这是一个非常基本的问题,但我尝试了很多东西。我的最后一个代码是:

import csv
with open ('C:\Users\Michel Spiero\Desktop\Base de dados para curso de Python/enrollments.csv') as csvfile:
    readCSV =csv.reader(csvfile, delimiter=',')

    for row in readCSV:
        print(row)

我收到此错误:

File "<ipython-input-9-3103e7dc9e55>", line 3
    with open ('C:\Users\Michel Spiero\Desktop\Base de dados para curso de Python/enrollments.csv') as csvfile:
              ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

我该怎么办?

由于

1 个答案:

答案 0 :(得分:2)

反斜杠U(\U)在字符串文字中有特殊含义。文档中的String and Bytes literals表示\Uxxxxxxxx的含义是“32位十六进制值xxxxxxxx的字符”

所以你必须至少逃脱用户U之前的反斜杠,或者在字符串前放一个r,这样反斜杠才有特殊含义。