簡體   English   中英

將列表列表寫入 csv 並在 python 中出現 UnicodeEncodeError

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

我正在使用 openpyxl 庫將 xlsm 文件轉換為 csv。 我遇到的問題是,當我嘗試將列表列表傳遞給 csv python 時返回以下錯誤:

回溯(最后一次調用):文件“test.py”,第 21 行,在 listIntoCsv(finalList) 文件“test.py”,第 16 行,在 listIntoCsv write.writerows(list) UnicodeEncodeError: 'ascii' codec can't在 position 20 中編碼字符 u'\xfa':序數不在范圍內(128)

這些是最終列表中 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]]

我正在用 python2 執行代碼。 我嘗試應用不同的解決方案,使代碼如下所示:

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