我试图将CSV文件读入Python (Spyder),但我一直得到一个错误。我的代码:

import csv

data = open("C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")
data = csv.reader(data)
print(data)

我得到以下错误:

SyntaxError (unicode错误)“unicodesescape”编解码器不能解码字节 在位置2-3:截断\UXXXXXXXX转义

我试过把\换成\\或者/,还试过在“C”前面加一个r。,但所有这些都不起作用。


当前回答

你可以把r放在你实际路径的字符串前面,它表示一个原始字符串。例如:

data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")

其他回答

字符串中的第一个反斜杠将被解释为一个特殊字符。事实上,因为它后面跟着一个“U”,所以它被解释为Unicode码位的开始。

要解决这个问题,需要转义字符串中的反斜杠。直接的方法是通过双反斜杠:

data = open("C:\\Users\\miche\\Documents\\school\\jaar2\\MIK\\2.6\\vektis_agb_zorgverlener")

如果你不想在字符串中转义反斜杠,并且你不需要在字符串中使用转义码或引号,你可以使用“原始”字符串,在它前面使用“r”,如下所示:

data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")

根据字符串字面量:

String literals can be enclosed within single quotes (i.e. '...') or double quotes (i.e. "..."). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash character (i.e. \) is used to escape characters which otherwise will have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter r or R. Such strings are called raw strings and use different rules for backslash escape sequences. In triple-quoted strings, unescaped newlines and quotes are allowed, except that the three unescaped quotes in a row terminate the string. Unless an r or R prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C.

所以理想情况下你需要替换这一行:

data = open("C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")

致下列任何一个字符:

使用原始前缀和单引号(即“…”): data = open(r' c:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener') 使用双引号(即"…")和转义反斜杠字符(即\): data = open("C:\\Users\\miche\\Documents\\school\\jaar2\\MIK\\2.6\\vektis_agb_zorgverlener") 使用双引号(即"…")和正斜杠字符(即/): data = open("C:/Users/miche/Documents/school/jaar2/MIK/2.6/vektis_agb_zorgverlener")

你可以把r放在你实际路径的字符串前面,它表示一个原始字符串。例如:

data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")

它通过中和“by f = open(' f:\\file.csv')”来为我工作。

尝试将文件路径写为“C:\\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener”,即在驱动器后加双反斜杠,而不是“C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener”