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

求助: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:

  1. Encoding fix: By adding encoding='utf-8' to the open() call, Python correctly parses the special Unicode symbols in your file. If UTF-8 doesn't work for some reason, try encoding='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).
  2. 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 satisfy idx % 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.reader was 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:07:46