从Python中的文件中删除JSON对象 [英] Remove JSON object from file in Python
问题描述
我不确定json文件是否唯一,但是找不到其他有效的问题/答案.
I'm not sure if my json file is unique but I couldn't find any other question/answers that worked.
我的JSON文件如下:
My JSON file looks like:
{"UserID": "name1", "Timestamp": "1234"}
{"UserID": "name2", "Timestamp": "4321"}
{"UserID": "name3", "Timestamp": "1234"}
python是否有办法从文件中删除整行?
Is there a way for python to delete an entire line from the file?
这是我到目前为止所做的:
This is what I've done so far:
open_file = open("times.json", 'r')
line = open_file.readline()
while line:
jsonLine = json.loads(line)
if line['Timestamp'] == '1234':
del line
open_file.close()
如果时间戳为1234,则我希望它删除整个对象,因此文件将如下所示:
If the timestamp is 1234, I want it to delete the entire object so the file will just look like this:
{"UserID": "name2", "Timestamp": "4321"}
谢谢!
推荐答案
结合jonrsharpe和ajon的建议,而不是在阅读时将其删除,而是将其读入内存,然后再写回.
Combining both jonrsharpe's and ajon's suggestions, instead of deleting it while reading, read it into memory and then write it back.
但是,您可能有一个更轻松的时间来先阅读 json
,然后消除具有匹配元素的行,而不是直接操作文本:
You might however have an easier time to read the json
s first and then eliminate the lines with matched elements, instead of manipulating the text directly:
json_lines = []
with open("times.json", 'r') as open_file:
for line in open_file.readlines():
j = json.loads(line)
if not j['Timestamp'] == '1234':
json_lines.append(line)
with open("times.json", 'w') as open_file:
open_file.writelines('\n'.join(json_lines))
与在行中专门查找"TimeStamp":"1234"
的情况相比,此方法在必要时为您提供了多个键/值的更多条件灵活性.
This method gives you more conditional flexibility over multiple keys/values if necessary as opposed to looking specifically for "TimeStamp": "1234"
within the line.
这篇关于从Python中的文件中删除JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!