在csv文件中写入数据时出现python错误

时间:2017-01-09 20:42:35

标签: python

写一个python程序在.csv文件中写入数据,但是发现.csv中的每个项目在内容之前都有一个“b”,并且有空行,我不知道如何删除空白行; .csv文件中的某些项目是无法识别的字符,例如“b'\ xe7 \ xbe \ x85 \ xe5 \ xb0 \ x91 \ xe5 \ x90 \ x9b'”,因为有些数据是中文和日文,所以我认为在.csv文件中写入这些数据时可能出错了。请帮我解决问题 该计划是:

#write data in .csv file
def data_save_csv(type,data,id_name,header,since = None):
    #get the date when storage data
    date_storage()
    #create the data storage directory
    csv_parent_directory = os.path.join("dataset","csv",type,glovar.date)
    directory_create(csv_parent_directory)
    #write data in .csv
    if type == "group_members":
        csv_file_prefix = "gm"
    if since:
        csv_file_name = csv_file_prefix + "_" + since.strftime("%Y%m%d-%H%M%S") + "_" + time_storage() + id_name + ".csv"
    else:
        csv_file_name = csv_file_prefix + "_"  + time_storage() + "_" + id_name + ".csv"
    csv_file_directory = os.path.join(csv_parent_directory,csv_file_name)

    with open(csv_file_directory,'w') as csvfile:

        writer = csv.writer(csvfile,delimiter=',',quotechar='"',quoting=csv.QUOTE_MINIMAL)

        #csv header
        writer.writerow(header)

        row = []
        for i in range(len(data)):
            for k in data[i].keys():
                row.append(str(data[i][k]).encode("utf-8"))
            writer.writerow(row)
            row = []

the .csv file

2 个答案:

答案 0 :(得分:1)

你有几个问题。时髦的" b"之所以发生这种情况是因为csv会在将数据添加到列之前将数据转换为字符串。当您执行str(data[i][k]).encode("utf-8")时,您获得了一个bytes对象,其字符串表示形式为b"...",并且其中填充了utf-8编码数据。您应该在打开文件时处理编码。在python 3中,open打开一个文件,其中包含来自sys.getdefaultencoding()的编码,但最好明确说明您要编写的内容。

接下来,没有任何内容表明两个dicts将以相同的顺序枚举其键。 csv.DictWriter类用于从字典中提取数据,因此请使用它。在我的示例中,我假设header具有您想要的键的名称。可能header不同,在这种情况下,您还需要传入您想要的实际dict密钥名称。

最后,你可以在写行时删除空的dicts。

with open(csv_file_directory,'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=header, delimiter=',',
        quotechar='"',quoting=csv.QUOTE_MINIMAL)
    writer.writeheader()
    writer.writerows(d for d in data if d)

答案 1 :(得分:0)

听起来至少你的一些问题与不正确的unicode有关。

尝试将下面的代码段实现到现有代码中。正如评论所说,第一部分将您的输入转换为utf-8。

第二位将以ascii的预期格式返回输出。

import codecs
import unicodedata

f = codecs.open('path/to/textfile.txt', mode='r',encoding='utf-8') #Take input and turn into unicode
    for line in f.readlines():
    line = unicodedata.normalize('NFKD', line).encode('ascii', 'ignore'). #Ensure output is in ASCII
相关问题