2016-08-11 23 views
0

私はこのプログラム読み取りエラーのcsvファイルunicodeescape

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) 

を持っていますか?

with open("C:\Users\frederic\Desktop\WinPython-64bit-3.4.4.3Qt5\notebooks\scores.txt","r") as scoreFile: ^SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape.

+0

with open('eggs.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print ', '.join(row) 
[PythonのオープンファイルのUnicodeエラー(http://stackoverflow.com/questions/18276283/python-open-file-unicode-error)の可能性の重複 –

答えて

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: 
0

あなたが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()は無用であるにも注意してください:

with文はtryおよびcatchを交換してください。また、 はブロックの後に自動的にファイルを閉じます。つまり、scoreFile.close()行を削除できます。

また、あなたがPEP8によるラインif len(row) != 0 を変更することができます。

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Yes: if not seq: if seq:

No: if len(seq): if not len(seq):

最後に一つ、あなたのfor loopは、あなたがより良い最初docからの例のコピーを開始csv読み取るために、どちらか良いではありません!

関連する問題