
本文详解如何在 Python 文件处理中避免因非法字符串转整数引发的 ValueError: invalid literal for int() with base 10 错误,通过预校验(如 str.isdigit())和健壮异常处理,确保程序稳定解析含数字与非数字混合的文本结构。
本文详解如何在 python 文件处理中避免因非法字符串转整数引发的 `valueerror: invalid literal for int() with base 10` 错误,通过预校验(如 `str.isdigit()`)和健壮异常处理,确保程序稳定解析含数字与非数字混合的文本结构。
该错误的根本原因在于:代码假设文件中偶数行(索引 0, 2, 4...)必定是纯数字字符串,并直接调用 int(lines[i]) 尝试转换。但若该行为空、含空格、换行符、字母或符号(如 "5\n" 未 strip、" 10 " 或 "abc"),int() 即刻抛出 ValueError。
✅ 正确做法是:先清洗 + 再验证 + 后转换。关键步骤包括:
- 使用 .strip() 去除首尾空白(包括 \n, \r, \t, 空格);
- 使用 .isdigit() 判断是否为非负纯数字字符串(注意:"-5" 或 "5.0" 返回 False,符合本场景安全需求);
- 对非法行提供友好提示,而非中断整个流程;
- 避免在 try/except/finally 中嵌套函数定义(易引发作用域与执行顺序问题)——应将函数定义移至 if __name__ == '__main__': 外部。
以下是优化后的完整可运行示例:
def encrypt(file_path):
"""从指定文件按“数字行+文本行”交替格式加密:取每组文本的前N个字符(N=数字行值)"""
result = ""
try:
with open(file_path, "r", encoding="utf-8") as f:
lines = f.readlines()
# 每两行一组:第i行为count,第i+1行为word
for i in range(0, len(lines), 2):
if i + 1 >= len(lines): # 防止越界:最后一行无配对文本
print(f"Warning: Incomplete pair at line {i + 1} — missing text line")
break
count_line = lines[i].strip()
if count_line.isdigit():
count = int(count_line)
word = lines[i + 1].strip()
# 安全切片:即使 count > len(word),也不会报错
result += word[:count] + " "
else:
print(f"Warning: Invalid integer on line {i + 1}: '{count_line}' (skipped)")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return ""
except Exception as e:
print(f"Unexpected error: {e}")
return ""
return result.strip()
# 主程序入口
if __name__ == '__main__':
print("Starting encryption...")
encrypted_string = encrypt("test.txt")
print("Encrypted result:", repr(encrypted_string))
print("hello world") # 替代原代码中冗余的 [print(...)] 行? 重要注意事项:
- str.isdigit() 仅识别 Unicode 数字字符(如 '123', '①②③'),不支持负号、小数点或空格。若需支持负数,应改用 try/except int() 捕获;
- 总是检查 i + 1 < len(lines),防止 IndexError;
- 使用 word[:count] 是安全的(Python 切片自动截断),无需额外长度判断;
- 显式指定 encoding="utf-8" 避免跨平台读取乱码;
- 原代码中 encrypt = " " 初始化会导致结果开头多一个空格,已修正为 ""。
通过以上改进,程序具备强健性、可维护性和清晰的错误反馈能力,真正实现“容错式文件解析”。

















