使用非ascii将xls转换为csv的Python脚本

使用非ascii将xls转换为csv的Python脚本,python,excel,csv,non-ascii-characters,Python,Excel,Csv,Non Ascii Characters,我有一个脚本,请参见下文,当xls包含ascii数据时,它可以正常工作。我尝试过在不同的地方添加utf-8,但当xls包含非ascii时,脚本仍然失败 #!/usr/bin/env python import xlrd import csv book = xlrd.open_workbook('/Users/admin/Documents/PythonScripts/an_excel_file.xls') # Assuming the fist sheet is of interest

我有一个脚本,请参见下文,当xls包含ascii数据时,它可以正常工作。我尝试过在不同的地方添加utf-8,但当xls包含非ascii时,脚本仍然失败

#!/usr/bin/env python

import xlrd
import csv

book = xlrd.open_workbook('/Users/admin/Documents/PythonScripts/an_excel_file.xls')

# Assuming the fist sheet is of interest 
sheet = book.sheet_by_index(0)

# Many options here to control how quotes are handled, etc.
csvWriter = csv.writer(open('/Users/admin/Documents/PythonScripts/a_csv_file.csv', 'w'), delimiter=',') 

for i in range(sheet.nrows):
    csvWriter.writerow(sheet.row_values(i))

你知道我如何添加这个吗?

这就是我如何解决UTF-8数据问题的方法。希望这有帮助

your_csv_file = open('myfile.csv'), 'wb')
wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
for rownum in xrange(worksheet.nrows):
    wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)])
your_csv_file.close()

您可以选择此处提供的源代码:

您好,谢谢您的反馈,但它会生成一个空白的csv。我基本上是在尝试使用Python打开一个xls文件“file.xls”,然后作为csv重新保存。除非字段中有“é”或“'”,否则一切正常。有什么想法吗?你的意思是它运行时会产生一个空白的csv吗?