Python Utf-8写入CSV

Python Utf-8写入CSV,python,csv,utf-8,Python,Csv,Utf 8,我无法将已编码的数据保存到CSV中。我可以在之后解码CSV文件,但我宁愿在之前进行所有数据清理。我设法只保存文本,但当我添加时间戳时,这是不可能的 我做错了什么?我读到如果srt()和.encode()不起作用,应该尝试.join,但仍然无效 错误: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128) 代码: 首先,确保使用正确的方法处理JSON数据

我无法将已编码的数据保存到CSV中。我可以在之后解码CSV文件,但我宁愿在之前进行所有数据清理。我设法只保存文本,但当我添加时间戳时,这是不可能的

我做错了什么?我读到如果
srt()
.encode()
不起作用,应该尝试
.join
,但仍然无效

错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128) 
代码:


首先,确保使用正确的方法处理JSON数据

接下来,不要捕获
BaseException
,您没有理由在这里捕获内存错误或键盘中断。而是捕获更具体的异常

接下来,在写入之前对数据进行编码:

def on_data(self, data):
    try:
        tweet = json.loads(data)['text']
    except (ValueError, KeyError), e:
        # Not JSON or no text key
        print 'fail on data {}'.format(data)
        return

   with open('twitDB.csv', 'a') as save_file:
        save_file.write(tweet.encode('utf8') + '\n')
        return True

为什么要手动拆分JSON数据?改用
json
模块;e、 g.
tweet=json.load(数据)['text']
。这会产生一个Unicode值。好的,谢谢你,我们会研究一下的
def on_data(self, data):
    try:
        tweet = json.loads(data)['text']
    except (ValueError, KeyError), e:
        # Not JSON or no text key
        print 'fail on data {}'.format(data)
        return

   with open('twitDB.csv', 'a') as save_file:
        save_file.write(tweet.encode('utf8') + '\n')
        return True