我试图将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。,但所有这些都不起作用。
字符串中的第一个反斜杠将被解释为一个特殊字符。事实上,因为它后面跟着一个“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")
发生此错误是因为您正在使用普通字符串作为路径。您可以使用以下三种解决方案之一来解决问题:
1:把r放在普通字符串前面。它将普通字符串转换为原始字符串:
pandas.read_csv(r"C:\Users\DeePak\Desktop\myac.csv")
2:
pandas.read_csv("C:/Users/DeePak/Desktop/myac.csv")
3:
pandas.read_csv("C:\\Users\\DeePak\\Desktop\\myac.csv")
根据字符串字面量:
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")