2 回答
TA贡献1895条经验 获得超3个赞
问题可能是a.readlines()因为它将整个文件带到您的记忆中。在处理大文件时,逐行读取它会更有趣,如下所示:
with open(fname) as f:
for line in f:
# Do your magic here, on this loop
# No need to close it, since the `with` will take care of that.
如果您的目标是$用 a替换 each \n,它将是这样的:
with open(fname, "r+") as f:
for line in f:
line.replace("$", "\n")
TA贡献1875条经验 获得超5个赞
为了能够处理可能的$字符的字符串中的JSON对象,你可以拆分输入字符串data1与$成片段,由一个加盟片段转换成字符串一个,直到它可解析为JSON,点你输出该串并清楚地继续下一个片段:
import json
candidate = ''
for fragment in data1.split('$'):
candidate += fragment
try:
json.loads(candidate)
print(candidate)
candidate = ''
except json.decoder.JSONDecodeError:
candidate += '$'
continue
data1 = '''{}${"a":"$"}${"b":{"c":2}}'''例如,给定,这输出:
{}
{"a":"$"}
{"b":{"c":2}}
添加回答
举报