从文本文件读取字典时使用eval出现Traceback报错,求解决方法
问题分析与解决方案
你的问题出在文件内容格式和eval()的使用限制上,我来帮你拆解和解决:
你的文本文件里是两条变量赋值语句:
account1 = {'email':'abc@test1', 'password':'abc321', 'securitycode':546987, 'name':'tester1', 'phone':236945744 } account2 = {'email':'abc@test2.com', 'password':'abc123', 'securitycode':699999, 'name':'tester2', 'phone':666666666666 }
但eval()只能处理单个可求值的表达式,它没法直接执行多条赋值语句,这就是你触发Traceback报错的核心原因。
下面给你几种可行的解决办法:
方法1:修改文件格式(最简单直接)
把文件里的两个字典放到一个列表中,让整个内容变成单个可求值的表达式:
[ {'email':'abc@test1', 'password':'abc321', 'securitycode':546987, 'name':'tester1', 'phone':236945744 }, {'email':'abc@test2.com', 'password':'abc123', 'securitycode':699999, 'name':'tester2', 'phone':666666666666 } ]
之后你的原代码就能正常运行:
dicts_from_file = [] with open('account.txt','r') as inf: dicts_from_file = eval(inf.read()) print(dicts_from_file)
方法2:用exec()处理原文件(不修改文件)
如果不想改动原文件,可以用exec()来执行文件里的代码,再从局部命名空间中提取目标变量:
dicts_from_file = [] with open('account.txt','r') as inf: content = inf.read() # 创建局部命名空间,避免污染全局变量 local_vars = {} exec(content, globals(), local_vars) # 收集所有以"account"开头的变量值(也就是你的字典) for key, value in local_vars.items(): if key.startswith('account'): dicts_from_file.append(value) print(dicts_from_file)
方法3:改用JSON格式(最安全推荐)
eval()和exec()都存在安全风险——如果文件被恶意篡改,可能会执行危险代码。更稳妥的方式是用JSON格式存储数据:
将account.txt修改为JSON数组:
[ {"email":"abc@test1", "password":"abc321", "securitycode":546987, "name":"tester1", "phone":236945744}, {"email":"abc@test2.com", "password":"abc123", "securitycode":699999, "name":"tester2", "phone":666666666666} ]
然后用Python内置的json模块读取:
import json dicts_from_file = [] with open('account.txt','r') as inf: dicts_from_file = json.load(inf) print(dicts_from_file)
内容的提问来源于stack exchange,提问作者M.Naveed
相关产品推荐
相关产品推荐

