提问人:Shinji_LinX 提问时间:11/5/2023 更新时间:11/5/2023 访问量:20
不正确地覆盖 JSON 文件
incorrect overwriting of a json file
问:
我需要在文件中找到值,然后删除块,但我遇到了麻烦。
def fineder(filename='C:\\path\\config.json'):
with open(filename, 'r+') as file:
file_data = json.load(file)
for item in file_data['inbounds'][1]['settings']['clients']:
print(item)
if item['id'] == 'xxxxxxxxxx':
for key in ['id', 'email', 'flow']:
item.pop(key, '')
if not item:
file_data['inbounds'][1]['settings']['clients'].remove(item)
file.seek(0)
json.dump(file_data, file, indent=4)
处理后,会在文件末尾添加一个额外的块,从而破坏文件结构。结果,我得到以下输出:
{
"log": {
"loglevel": "info"
},
"routing": {
"rules": [],
"domainStrategy": "AsIs"
},
"inbounds": [
{
"port": 23,
"tag": "ss",
"protocol": "shadowsocks",
"settings": {
"method": "2022-blake3-aes-128-gcm",
"password": "aaaaaaaaaaaaaaaa24356475bbbbbbbbbbbbbbbb",
"network": "tcp,udp"
}
},
{
"port": 443,
"protocol": "vless",
"tag": "vless_tls",
"settings": {
"clients": [
{
"id": "xyxyxyxyxyxy",
"email": "user1@myserver",
"flow": "xtls-rprx-vision"
},
{
"id": "ofofofofofofo",
"email": "user2@myserver",
"flow": "xtls-rprx-vision"
},
{
"id": "xxxxxxxxxx",
"email": "user3@myserver",
"flow": "xtls-rprx-vision"
},
{
"id": "hfhfhfhhfhfhfh",
"email": "user4@myserver",
"flow": "xtls-rprx-vision"
},
{
"id": "ldldldldldld",
"email": "test@myserver",
"flow": "xtls-rprx-vision"
},
{
"id": "assasasasasas",
"email": "testxtls1@myserver",
"flow": "xtls-rprx-vision"
}
],
"decryption": "none",
"fallbacks": [
{
"path": "/myverysecretpath",
"dest": "@vless-ws"
},
{
"dest": "8080"
}
]
},
"streamSettings": {
"network": "tcp",
"security": "tls",
"tlsSettings": {
"alpn": [
"http/1.1",
"h2"
],
"certificates": [
{
"certificateFile": "/myverysecretpath/file.key",
"keyFile": "/myverysecretpath/file.pem"
}
]
}
},
"sniffing": {
"enabled": true,
"destOverride": [
"http",
"tls"
]
}
},
{
"listen": "@vless-ws",
"protocol": "vless",
"tag": "vless_ws",
"settings": {
"clients": [
{
"id": "nvnvnvnvnnv",
"email": "user2@myserver"
},
{
"id": "nvnvnvnnvnv",
"email": "test@myserver",
},
{
"id": "cxvnvbcnbcvn",
"email": "testwebsocket@myserver"
}
],
"decryption": "none"
},
"streamSettings": {
"network": "ws",
"security": "none",
"wsSettings": {
"path": "/myverysecretpath"
}
}
}
],
"outbounds": [
{
"protocol": "freedom",
"tag": "direct"
},
{
"protocol": "blackhole",
"tag": "block"
}
]
} }
}
],
"outbounds": [
{
"protocol": "freedom",
"tag": "direct"
},
{
"protocol": "blackhole",
"tag": "block"
}
]
}
有趣的是,当我在写入文件之前打印时,没有这样的事情。
with open('C:\\path\\setting.json', 'w') as blyat:
blyat.seek(0)
json.dump(file_data, blyat, indent=4)
我能够通过打开一个新文件进行写入来解决这个问题。但我认为这是一个糟糕的选择。谁能告诉我如何解决这个问题?
答: 暂无答案
评论