简体   繁体   English

将列表列表写入 csv 并在 python 中出现 UnicodeEncodeError

[英]Write a list of lists into csv and having UnicodeEncodeError in python

I am converting an xlsm file to csv using the openpyxl library.我正在使用 openpyxl 库将 xlsm 文件转换为 csv。 I have the problem that when I try to pass the list of lists to the csv python returns the following error:我遇到的问题是,当我尝试将列表列表传递给 csv python 时返回以下错误:

Traceback (most recent call last): File "test.py", line 21, in listIntoCsv(finalList) File "test.py", line 16, in listIntoCsv write.writerows(list) UnicodeEncodeError: 'ascii' codec can't encode character u'\xfa' in position 20: ordinal not in range(128)回溯(最后一次调用):文件“test.py”,第 21 行,在 listIntoCsv(finalList) 文件“test.py”,第 16 行,在 listIntoCsv write.writerows(list) UnicodeEncodeError: 'ascii' codec can't在 position 20 中编码字符 u'\xfa':序数不在范围内(128)

These are 2 example of 1 list inside the final list:这些是最终列表中 1 个列表的 2 个示例:

[[u'0@mediador.jordilazo.com', u'SZHK@jordilazo.es, NFUW@competencia.es', datetime.datetime(2022, 7, 18, 10, 7, 16), 1L, '0', 1L, 2L, 'NO', None, 'SZHK@competencia.es', 'NFUW@competencia.es', None, None, False, False, None, None, False, False, False, None, None, True, 'SI', 'N/A', 3182L, 0L, None, None, None, '#N/A', 'RE: NHYJIJJP< >LWWM', u'a7d2a497-e4f1-40b2-8dc8-699b270bbcd4', u'Comentario: \xd1<GRC?SST"&"\\ A', None], [u'MMUN19@jordilazo.com', u'SYPV@jordilazo.es, IFMT@competencia.es', datetime.datetime(2022, 7, 18, 9, 3, 49), 1L, 'MMUN19', 1L, 2L, 'NO', None, 'SYPV@competencia.es', 'IFMT@competencia.es', None, None, False, False, None, None, False, False, False, None, None, True, 'SI', 'N/A', 'SI', 'N/A', None, None, None, 'DGT Madrid', 'RE: NIPGGVJK< >FJRQ', u'2cd7a6f2-4ce4-4678-b592-bff465f9f411', u'Comentario: \xd1@GHJ<FCX"&"\\ A', None]]

I am executing the code with python2.我正在用 python2 执行代码。 I have tried to apply different solutions so that the code looks like this:我尝试应用不同的解决方案,使代码如下所示:

from openpyxl import load_workbook
import csv
import codec

  excelFile = load_workbook('test.xlsm', data_only=True)
  currentSheet = excelFile.worksheets[0]
  
  def iter_rows(currentSheet):
    for row in currentSheet.iter_rows():
      yield [cell.value for cell in row]

  def listIntoCsv(list):
    with codecs.open('test','w',encoding='UTF-8') as f:
      write = csv.writer(f)
      write.writerows(list)
  
  finalList = list(iter_rows(currentSheet))
  print(finalList)
  listIntoCsv(finalList)
from types import NoneType
import unicodedata
from openpyxl import load_workbook
import csv
from datetime import datetime
import os
     
  def iterRows(currentSheet):
    for row in currentSheet.iter_rows():
      yield [cell.value for cell in row]

  def listIntoCsv(list):
    with open('excel.csv','w') as f:
      write = csv.writer(f)
      write.writerows(list)
  
  def encodeList(list):
    for x,y in enumerate(list):
      for j,element in enumerate(y):

        if isinstance(element,unicode):
          element = unicodedata.normalize('NFKD', element).encode('ascii', 'ignore')
          list[x][j] = element

        elif isinstance(element,datetime):
          element = element.strftime('%d/%m/%Y-%H:%M:%S')
          list[x][j] = element

        elif isinstance(element,long):
          element = str(element)
          list[x][j] = element

        elif isinstance(element,NoneType):
          element = str(element).replace('None','Nada')
          list[x][j] = element

        elif isinstance(element,bool):
          element = str(element)
          list[x][j] = element

        else:
          list[x][j] = element
          
    return list

  ubicationExcel = 'bin/mailList/Investigacion_DLP_enmascarado.xlsm'
  excelFile = load_workbook(ubicationExcel, data_only=True)
  currentSheet = excelFile.worksheets[0]
  dirtyList = list(iterRows(currentSheet))
  finalList = encodeList(dirtyList)
  listIntoCsv(finalList)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM