我有兩個檔案:json 和文本檔案。
我想用文本檔案中的值替換字典值之一。
讓我們說,在文本檔案中file.text,我有以下串列。[11, 15, 10].
在json檔案中,我有以下字典。
"aa": {
"bb": [
"25",
"40",
"05"
],
"cc": [
"20"
]
}
我想cc用上面的文本檔案覆寫該值。
file.json
"aa": {
"bb": [
"25",
"40",
"05"
],
"cc": [
"11", "15", "10"
]
}
我在 Python 中嘗試過一些東西。
def replace(text_file, json_file):
tex_file_path = 'C:/Documents/file.txt'
with open(os.path.join(tex_file_path, text_file), 'r') as f:
read_text= f.read()
json_file_path = 'C:/Documents/file.json'
with open(os.path.join(json_file_path, json_file), 'r') as f:
read_json = json.load(f)
text_to_be_replaced = read_json.get('aa')
for value in text_to_be_replaced.items():
for element in value:
# statment
我想知道是否有人真的可以幫助解決這個問題。
uj5u.com熱心網友回復:
這是一個使用 aStringIO來演示從類檔案物件讀取/寫入的簡單示例:
import json
from io import StringIO
json_file_obj = StringIO("""
{"aa": {
"bb": [
"25",
"40",
"05"
],
"cc": [
"20"
]
}
}
""")
text_file_obj = StringIO("[11, 15, 10]")
def replace(src_file_obj: StringIO, repl_file_obj: StringIO):
# Load file contents into a Python object
data = json.load(src_file_obj)
# Read in txt file contents
new_cc_value = json.load(repl_file_obj)
# But now result will be a list of int, here we want a list of string
new_cc_value = list(map(str, new_cc_value))
# Replace desired value
data['aa']['cc'] = new_cc_value
# Now we write to our file-like object, `src_file_obj`
# This is to demonstrate replacing the original file contents
src_file_obj = StringIO()
json.dump(data, src_file_obj)
# Seek to the start of the file
src_file_obj.seek(0)
return src_file_obj
json_file_obj = replace(json_file_obj, text_file_obj)
print(json_file_obj.read())
輸出:
{"aa": {"bb": ["25", "40", "05"], "cc": ["11", "15", "10"]}}
提示- 如果要將輸出寫入實際檔案,可以替換以下這些行:
src_file_obj = StringIO()
json.dump(data, src_file_obj)
src_file_obj.seek(0)
使用這些行:
with open("file_name.txt", 'w') as out_file:
json.dump(data, out_file)
uj5u.com熱心網友回復:
盡管您已將它命名為.text,但檔案的內容似乎是 JSON,因此您也可以使用json.load()。然后將串列中的整數轉換為字串并將其插入到 JSON 檔案中的所需位置。
無需遍歷字典項。只需解決您要替換的特定元素。
def replace(text_file, json_file):
tex_file_path = 'C:/Documents'
with open(os.path.join(tex_file_path, text_file), 'r') as f:
read_text= json.load(f)
read_text = list(map(str, read_text))
json_file_path = 'C:/Documents'
with open(os.path.join(json_file_path, json_file), 'r') as f:
read_json = json.load(f)
read_json["aa"]["cc"] = read_text
with open(os.path.join(json_file_path, json_file), 'w') as f:
json.dump(read_json, f)
此外,您的XXX_path變數應該只是目錄,檔案名來自函式引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338286.html
