You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用iso-8859-1解析含瑞典字符CSV时遇UnicodeEncodeError问题求助

Fixing UnicodeEncodeError When Reading Swedish Characters from CSV in Python

Let's break down what's happening here: your code is correctly reading the CSV with iso-8859-1 encoding, but the error is actually occurring when you try to print the results. Python's default standard output encoding is often set to ASCII, which can't handle Swedish special characters like ä or ö.

Here are a few straightforward fixes to resolve this:

1. Reconfigure Standard Output to Use UTF-8

Force your script's output stream to use UTF-8, which supports all Unicode characters including Swedish ones:

import csv
import sys

# Set stdout to use UTF-8 encoding
sys.stdout.reconfigure(encoding='utf-8')

with open('test.csv', mode='r', encoding='iso-8859-1') as label_file:
    data = csv.reader(label_file, delimiter='\t')
    for row in data:
        print(row)

(Note: I swapped codecs.open with Python 3's built-in open since it natively supports the encoding parameter now—it's cleaner and more modern.)

2. Explicitly Encode/Decode Strings When Printing

If reconfiguring stdout isn't an option, you can handle encoding directly when printing:

import csv

with open('test.csv', mode='r', encoding='iso-8859-1') as label_file:
    data = csv.reader(label_file, delimiter='\t')
    for row in data:
        # Convert each row to a UTF-8 compatible string before printing
        print(', '.join(row).encode('utf-8').decode('utf-8'))

3. Verify Your Terminal's Encoding

Sometimes the issue is with your terminal/console, not the code. Make sure your terminal is set to use UTF-8 or iso-8859-1 encoding. Most modern terminals (like macOS Terminal, Windows Terminal, or Linux bash) let you adjust this in their settings.

Why This Happened

When you read the file with iso-8859-1, you're correctly converting the file's bytes into Unicode strings in Python. The problem arises when Python tries to send these Unicode strings to your terminal—if the terminal's default encoding doesn't support the special characters, it throws that UnicodeEncodeError.

内容的提问来源于stack exchange,提问作者Ashraful Islam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:55:41