我的csv文件有编码 - ' utf-8'。我需要将csv转换为具有相同编码的excel工作簿,但无法执行此操作。试过很多东西,但无法修复。这是代码片段。 NOte:使用xlsxwriter包
def csv_to_excel(input_file_path, output_file_path):
file_path = input_file_path
excel_file_path = output_file_path
wb = Workbook(excel_file_path.encode('utf-8', 'ignore'), {'encoding': 'utf-8'})
sheet1 = wb.add_worksheet(("anyname1").encode('utf-8','ignore'))
sheet2 = wb.add_worksheet(("anyname2").encode('utf-8','ignore'))
for filename in glob.glob(file_path):
(f_path, f_name) = os.path.split(filename)
w_tab = str(f_name.split('_')[2]).split('.')[0]
if (w_tab=="anyname1"):
w_sheet = sheet1
elif (w_tab=="anyname2"):
w_sheet = sheet2
spamReader = csv.reader(open(filename, "rb"), delimiter=',',quotechar='"')
row_count = 0
for row in spamReader:
for col in range(len(row)):
w_sheet.write(row_count,col,row[col])
row_count +=1
try:
os.remove(excel_file_path)
except:
pass
wb.close()
print "Converted CSVs to Excel File"
错误: 案例1:当我尝试按如下方式打开utf-8编码的csv文件时:
spamReader = csv.reader(io.open(filename, "r", encoding = 'utf-8'), delimiter=',',quotechar='"')
然后在迭代spamReader对象时获取错误 UnicodeEncodeError:' ascii'编解码器无法对字符u' \ u2013'进行编码。位置92:序数不在范围内(128)
案例2:当我尝试打开与上面代码片段中提到的二进制相同的csv文件时,我无法将其保存为utf-8编码的excel,因此在调用wb.close()时,收到错误如 UnicodeDecodeError:' ascii'编解码器不能解码位置12中的字节0xe2:序数不在范围内(128)
我刚开始学习python所以也许这不是一个大问题,但请帮助我。