这里的问题是,我可以从我的文件夹中删除行,但我不能选择它们作为类似的方式。
例如,我有一个包含3000行等内容的.json文件,我需要删除以"navig"
开头的行。我们如何修改Python代码?
with open("yourfile.txt", "r") as f:
lines = f.readlines()
with open("yourfile.txt", "w") as f:
for line in lines:
if line.strip("\n") != "nickname_to_delete":
f.write(line)
(代码取自另一个答案。)
发布于 2019-12-27 10:47:14
你可以这样做:
with open("yourfile.txt", "r") as f:
lines = f.readlines()
with open("yourfile.txt", "w") as f:
for line in lines:
if not line.startswith(YOUR_SEARCH_STRING):
f.write(line)
或者,如果您只想写入文件一次:
with open("yourfile.txt", "r") as f:
lines = f.readlines()
lines_to_write = [line for line in lines if not line.startswith(YOUR_SEARCH_SRING)]
with open("yourfile.txt", "w") as f:
f.write(''.join(lines_to_write))
发布于 2019-12-27 11:11:20
这个答案只适用于JSON文件,在这种情况下,这是一种健壮的工作方式:
import json
with open('yourJsonFile', 'r') as jf:
jsonFile = json.load(jf)
print('Length of JSON object before cleaning: ', len(jsonFile.keys()))
testJson = {}
keyList = jsonFile.keys()
for key in keyList:
if not key.startswith('SOMETEXT'):
print(key)
testJson[key] = jsonFile[key]
print('Length of JSON object after cleaning: ', len(testJson.keys()))
with open('cleanedJson', 'w') as jf:
json.dump(testJson, jf)
https://stackoverflow.com/questions/59499522
复制相似问题