读取csv文件unicodeescape时出错

时间:2016-08-11 11:50:36

标签: python csv unicode-escapes

我有这个程序

import csv

with open("C:\Users\frederic\Desktop\WinPython-64bit-3.4.4.3Qt5\notebooks\scores.txt","r") as scoreFile:
    # write = w, read = r, append = a
    scoreFileReader = csv.reader(scoreFile)
    scoreList = []
    for row in scoreFileReader:
        if len (row) != 0:
            scoreList = scoreList + [row]

scoreFile.close()

print(scoreList)

为什么会出现此错误?

  

与   开放(" C:\用户\弗雷德里克\桌面\ WinPython-64-3.4.4.3Qt5 \笔记本\ scores.txt"" R&#34)   作为得分文件:                ^ SyntaxError :( unicode错误)' unicodeescape'编解码器无法解码位置2-3中的字节:截断\ UXXXXXXXX转义。

2 个答案:

答案 0 :(得分:1)

您需要将原始字符串与Windows样式的文件名一起使用:

with open(r"C:\Users\frederic\Desktop\WinPython-64bit-3.4.4.3Qt5\notebooks\scores.txt", 'r') as scoreFile:
         ^^

否则,Python的字符串引擎认为\ U是Unicode转义序列的开头 - 当然在这种情况下它不是。

另外,请注意您的scoreFile.close()无用:

PEP8语句替换try和catch。它也是    阻止后自动关闭文件。这意味着您可以删除scoreFile.close()行。

此外,您可以更改第if len(row) != 0行 根据{{​​3}}:

  

对于序列,(字符串,列表,元组),请使用空的事实   序列是错误的。

     

是:如果不是seq:        如果seq:

     

否:如果len(seq):       如果不是len(seq):

最后一件事,你的for loop也不好,阅读csv你最好先从doc开始复制一个例子!

with open('eggs.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
       print ', '.join(row)

答案 1 :(得分:0)

你可以试试这个:

import csv
import io

def guess_encoding(csv_file):
    """guess the encoding of the given file"""
    with io.open(csv_file, "rb") as f:
        data = f.read(5)
    if data.startswith(b"\xEF\xBB\xBF"):  # UTF-8 with a "BOM"
        return ["utf-8-sig"]
    elif data.startswith(b"\xFF\xFE") or data.startswith(b"\xFE\xFF"):
        return ["utf-16"]
    else:  # in Windows, guessing utf-8 doesn't work, so we have to try
        try:
            with io.open(csv_file, encoding="utf-8") as f:
                preview = f.read(222222)
                return ["utf-8"]
        except:
            return [locale.getdefaultlocale()[1], "utf-8"]

encodings = guess_encoding(r"C:\Users\frederic\Desktop\WinPython-64bit-3.4.4.3Qt5\notebooks\scores.txt")[0])

# then your code with 
with open(r"C:\Users\frederic\Desktop\WinPython-64bit-3.4.4.3Qt5\notebooks\scores.txt","r", encoding=encodings[0]) as scoreFile: