当我运行我的代码(Python 3)时,我不断收到此错误:
Traceback (most recent call last):
File "country.py", line 16, in <module>
for row in csv_reader:
File "C:\Users\benny\Anaconda3\lib\csv.py", line 112, in __next__
row = next(self.reader)
File "C:\Users\benny\Anaconda3\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2247: character maps to <undefined>
我尝试了these solutions但没有工作。
如果通过添加encoding =&#39; UTF-8修复编码问题,代码只打印一行。如果我保留编码问题,它会在抛出错误之前打印大约700行。无论哪种方式,它仍然无法工作。
import csv
import country_converter as coco
with open('Interpol.csv', 'r') as csv_file, open('Interpol_Extra.csv', 'w', newline='') as new_file:
csv_reader = csv.DictReader(csv_file)
fieldnames = ['Case Happened - UN Region', 'Case Happened - Continent',
'Recovered - UN Region', 'Recovered - Continent'] + csv_reader.fieldnames
csv_writer = csv.DictWriter(new_file, fieldnames)
csv_writer.writeheader()
for row in csv_reader:
case_country_name = row['Case happened - Country']
recovered_country_name = row['Recovered - Country']
if case_country_name:
row['Case Happened - UN Region'] = coco.convert(names=case_country_name, to='UNregion')
row['Case Happened - Continent'] = coco.convert(names=case_country_name, to='Continent')
if recovered_country_name:
row['Recovered - UN Region'] = coco.convert(names=recovered_country_name, to='UNregion')
row['Recovered - Continent'] = coco.convert(names=recovered_country_name, to='Continent')
csv_writer.writerow(row)
答案 0 :(得分:0)
这是我最终使用的代码。
正如Arun在评论中所建议的,如果您遇到类似问题,请阅读this question上的所有答案。它有关于此问题的堆栈交换最简洁和最有用的信息。
然后重新检查您的代码以确保其有效。就我而言,最终修复了一些错误的缩进。
import csv
import country_converter as coco
with open('Interpol.csv', 'r', encoding="utf-8") as csv_file, open('Interpol_Extra.csv', 'w', newline='', encoding="utf-8") as new_file:
csv_reader = csv.DictReader(csv_file)
fieldnames = ['Case Happened - UN Region', 'Case Happened - Continent',
'Recovered - UN Region', 'Recovered - Continent'] + csv_reader.fieldnames
csv_writer = csv.DictWriter(new_file, fieldnames)
csv_writer.writeheader()
for row in csv_reader:
case_country_name = row['Case happened - Country']
recovered_country_name = row['Recovered - Country']
if case_country_name:
row['Case Happened - UN Region'] = coco.convert(names=case_country_name, to='UNregion')
row['Case Happened - Continent'] = coco.convert(names=case_country_name, to='Continent')
if recovered_country_name:
row['Recovered - UN Region'] = coco.convert(names=recovered_country_name, to='UNregion')
row['Recovered - Continent'] = coco.convert(names=recovered_country_name, to='Continent')
csv_writer.writerow(row)