使用iso-8859-1解析含瑞典字符CSV时遇UnicodeEncodeError问题求助
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

