求助:Python读取TXT文件特定行时无法识别特殊符号的问题
Hey there! Let's get this sorted out for you. The core issue here is file encoding—those special symbols (like ✌, , ) need a proper Unicode encoding (most likely UTF-8) to be read correctly, and your original code didn't specify an encoding, so Python was using your system's default encoding which can't handle these characters.
Here's a straightforward solution that fixes the encoding problem and efficiently filters the lines you need:
target_lines = [] file_path = r"C:/Users/.../Example1.txt" # Critical: Specify UTF-8 encoding to support special symbols with open(file_path, 'r', encoding='utf-8') as f: # Use enumerate to track line indices (starts at 0) for idx, line in enumerate(f): # Target lines are 2nd, 5th, 8th... (1-based) → indices 1,4,7... (0-based) if idx % 3 == 1: # Optional: Remove trailing newline character if you don't need it cleaned_line = line.rstrip('\n') target_lines.append(cleaned_line) # Check the result print(target_lines)
Why this works:
- Encoding fix: By adding
encoding='utf-8'to theopen()call, Python correctly parses the special Unicode symbols in your file. If UTF-8 doesn't work for some reason, tryencoding='utf-8-sig'(for files with a UTF-8 BOM) or check your file's actual encoding (you can use tools like Notepad++ to view this). - Efficient line filtering: Using
enumerate()lets us track each line's index directly. Since you want lines 2,5,8... (1-based), their 0-based indices are 1,4,7... which all satisfyidx % 3 == 1. This avoids loading the entire file into memory at once (great for large files!).
Your original code failed because:
- Without specifying an encoding, Python uses your system's default (e.g., CP1252 on Windows), which can't decode those special symbols.
- Using
csv.readerwas unnecessary here—your file is plain text separated by newlines, so iterating over the file object directly is simpler and more efficient.
Give this code a try, and it should handle both the special symbols and the line filtering perfectly!
内容的提问来源于stack exchange,提问作者Fab_Freak
相关产品推荐
相关产品推荐

