Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回编解码器。ascii_解码(输入,自身错误)[0]_Python - Fatal编程技术网

Python 返回编解码器。ascii_解码(输入,自身错误)[0]

Python 返回编解码器。ascii_解码(输入,自身错误)[0],python,Python,我正在阅读csv格式的歌曲文件,我不知道我做错了什么 import csv import os import random file = open("songs.csv", "rU") reader = csv.reader(file) for song in reader: print(song[0], song[1], song[2]) file.close() 这就是错误: Traceback (most recent call last): File "/Users/

我正在阅读csv格式的歌曲文件,我不知道我做错了什么

import csv
import os
import random

file = open("songs.csv", "rU")
reader = csv.reader(file)

for song in reader:
    print(song[0], song[1], song[2])

file.close()
这就是错误:

Traceback (most recent call last):
  File "/Users/kuku/Desktop/hey/mine/test.py", line 10, in <module>
    for song in reader:
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 414: ordinal not in range(128)
回溯(最近一次呼叫最后一次):
文件“/Users/kuku/Desktop/hey/mine/test.py”,第10行,在
对于歌曲阅读器:
文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py”,第26行,解码
返回编解码器。ascii_解码(输入,自身错误)[0]
UnicodeDecodeError:“ascii”编解码器无法解码位置414处的字节0xe2:序号不在范围内(128)
试试看


使用这段代码:

for song in reader:
    print( song[0], song[1],song[2])
在循环的每个迭代过程中,您都在
读卡器中打印行的元素0、1和2。如果总共少于3个元素,这将导致(不同的)错误

如果您不知道每行中至少有3个元素,则可以将代码包含在
try
块中,但
块除外:

with open("songs.csv", "r") as f:
    song_reader = csv.reader(f)
    for song_line in song_reader:
        lyric = song_line
        try:
            print(lyric[0], lyric[1], lyric[2])
        except:
            pass # ...or preferably do something better

值得注意的是,在大多数情况下,最好使用
块打开
中的文件,如上所示。这样就不需要
file.close()

您可以用utf-8编码打开文件

file = open("songs.csv", "rU", encoding="utf-8")

请编辑您的帖子,以便我们可以清楚地看到代码的哪一部分。我建议您使用“with”语法打开文件,这样文件将在with block之后自动关闭。csv模块文档中有一些示例,其中有一些示例说明如何使用特定的编码器:在尝试所有代码后,我仍然会遇到相同的错误。有没有一种不用for循环的方法呢?我不知道为什么会出现错误,我无法复制。您可以使用
readlines()
(无
for
循环)读取所有行,即
歌词=f.readlines()
谢谢这首歌,csv文件已损坏,这就是我收到错误的原因
file = open("songs.csv", "rU", encoding="utf-8")