我有一个关于Python 2.7读/写csv文件的问题' utf-8-sig
'代码,我的csv。标题是
['\xef\xbb\xbfID;timestamp;CustomerID;Email']
我从文件"\xef\xbb\xbfID"
读取了一些代码(A.csv
),我希望将相同的代码和标题写入文件B.csv
我的打印日志显示:
['\xef\xbb\xbfID;timestamp;CustomerID;Email']
但实际的输出文件标题看起来像是
ÔªøID;timestamp
以下是代码:
def remove_gdpr_info_from_csv(file_path, file_name, temp_folder, original_header):
new_temp_folder = tempfile.mkdtemp()
new_temp_file = new_temp_folder + "/" + file_name
# Blanked new file
with open(new_temp_file, 'wb') as outfile:
writer = csv.writer(outfile, delimiter=";")
print original_header
writer.writerow(original_header)
# File from SFTP
with open(file_path, 'r') as infile:
reader = csv.reader(infile, delimiter=";")
first_row = next(reader)
email = first_row.index('Email')
contract_detractor1 = first_row.index('Contact Detractor (Q21)')
contract_detractor2 = first_row.index('Contact Detractor (Q20)')
contract_detractor3 = first_row.index('Contact Detractor (Q43)')
contract_detractor4 = first_row.index('Contact Detractor(Q26)')
contract_detractor5 = first_row.index('Contact Detractor(Q27)')
contract_detractor6 = first_row.index('Contact Detractor(Q44)')
indexes = []
for column_name in header_list:
ind = first_row.index(column_name)
indexes.append(ind)
for row in reader:
output_row = []
for ind in indexes:
data = row[ind]
if ind == email:
data = ''
elif ind == contract_detractor1:
data = ''
elif ind == contract_detractor2:
data = ''
elif ind == contract_detractor3:
data = ''
elif ind == contract_detractor4:
data = ''
elif ind == contract_detractor5:
data = ''
elif ind == contract_detractor6:
data = ''
output_row.append(data)
writer.writerow(output_row)
s3core.upload_files(SPARKY_S3, DESTINATION_PATH, new_temp_file)
shutil.rmtree(temp_folder)
shutil.rmtree(new_temp_folder)
答案 0 :(得分:5)
'\xef\xbb\xbf'
是unicode ZERO WIDTH NO-BREAK SPACE U + FEFF的UTF8编码版本。它通常用作unicode文本文件开头的字节顺序标记:
'\xef\xbb\xbf'
时,文件是utf8编码的'\xff\xfe'
,那么该文件是utf16 little endian '\xfe\xff'
时,文件是utf16大端 'utf-8-sig'
编码明确要求在文件开头写入此BOM
要在Python 2中的csv文件的读取时自动处理它,您可以使用编解码器模块:
with open(file_path, 'r') as infile:
reader = csv.reader(codecs.EncodedFile(infile, 'utf8-sig', 'utf8'), delimiter=";")
EncodedFile
将通过在utf8-sig
中对其进行解码来包装原始文件对象,实际上跳过BOM并在utf8
中重新编码它而没有BOM。
答案 1 :(得分:0)
您要像Serge Ballesta的回答一样,使用EncodedFile
库中的codecs
方法。
但是,使用Python 2.7编码utf-8-sig
不是UTF8-sig编码受支持的别名,您需要使用utf_8_sig
。另外,方法属性的顺序需要首先定义输出数据编码,然后定义文件编码:codecs.EncodedFile(file,datacodec,filecodec=None,errors=’strict')
这是完整的结果:
import codecs
with open(file_path, 'r') as infile:
reader = csv.reader(codecs.EncodedFile(infile, 'utf8', 'utf_8_sig'), delimiter=";")