我是CS的一年级学生,尝试调试一个简单的Python脚本。在
该脚本试图解析JSON文件的目录,也就是AWS存储桶。但是,我不知道这些错误是从哪里来的:
import json
import os
from pprint import pprint
jsonDirectory = "/path/to/dir/"
targetRegion = "-insert-region-here"
print("Searching for records with AWS Region: " + targetRegion)
print("")
for filename in os.listdir(jsonDirectory):
print("Reading: " + filename)
data = json.dumps(open(jsonDirectory + filename))
for i in range(len(data["Records"])):
if data["Records"][i]["awsRegion"] == targetRegion:
print("---------------------------")
print("Record #" + str(i))
print("Username: " + data["Records"][i]["userIdentity"] ["userName"])
print("Event name: " + data["Records"][i]["eventName"])
print("Event time: " + data["Records"][i]["eventTime"])
print("---------------------------")
print("")
print("Completed reading files.")
错误:
Traceback (most recent call last): File "/path/to/file.py", line 13, in data = json.dumps(open(jsonDirectory + filename)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/init.py", line 231, in dumps return _default_encoder.encode(obj) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 180, in default o.class.name) TypeError: Object of type 'TextIOWrapper' is not JSON serializable
让我假设您不在西欧或美国,并且默认编码不是
UTF-8
或者通常非常兼容的东西,比如iso-8859-1
。从上面的评论来看如果你把这句话分开:
^{pr2}$您将看到错误发生在
^{3}$fdata = f.read()
。建议是:如果您不确定,请尝试强制
open
忽略/绕过错误。来自Python文档:https://docs.python.org/3/library/functions.html#open从
ignore
开始,如下所示:并检查输出是否满足您的要求或哪里出了问题。在
相关问题 更多 >
编程相关推荐