Python 3.7如何实现文本/JSON文件键值的搜索更新与新增?
Great call switching to JSON for this task—working with key-value pairs becomes way more straightforward compared to hacking plain text files. Your current code only handles line-by-line replacement, but JSON’s native dictionary structure in Python makes updating/adding keys trivial. Here’s how to implement your exact requirement:
Step-by-Step Implementation
First, let’s outline the core logic:
- Load existing JSON data (initialize an empty dictionary if the file doesn’t exist)
- Parse your input string (e.g.,
C3:21,40orC5:32,11) into a key and value - Update the dictionary: overwrite the value if the key exists, add a new key-value pair if it doesn’t
- Save the updated dictionary back to the JSON file
Full Code Example
import json import os def parse_input(input_str): """Parse input strings like 'C3:21,40' into a key and value""" key, value = input_str.split(':', 1) return key.strip(), value.strip() def update_key_value(file_path, input_str): # Load existing data or initialize empty dict if os.path.exists(file_path): with open(file_path, 'r') as f: try: data = json.load(f) except json.JSONDecodeError: # Handle corrupted JSON by resetting to empty dict data = {} else: data = {} # Parse and update data key, value = parse_input(input_str) data[key] = value # Write updated data back to file (formatted for readability) with open(file_path, 'w') as f: json.dump(data, f, indent=4) # Test the function update_key_value('data.json', 'C3:21,40') # Updates existing C3 entry update_key_value('data.json', 'C5:32,11') # Adds new C5 entry
Optional: Store Values as Numeric Lists
If you want to work with the numeric values (instead of raw strings), modify the parse_input function to convert the value into a list of integers:
def parse_input(input_str): key, value_part = input_str.split(':', 1) value = [int(num.strip()) for num in value_part.split(',')] return key.strip(), value
This will store entries like {"C3": [21, 40]} in the JSON file, making it easier to perform calculations later.
Why This Is Better Than Your Original Text File Approach
Your current fileinput code works for simple line replacement, but it has limitations:
- You’d have to manually search each line for the target key, which is error-prone if lines are formatted inconsistently
- Adding new keys would require appending to the file, which adds extra logic
- JSON handles all the serialization/deserialization automatically, so you don’t have to worry about formatting edge cases
内容的提问来源于stack exchange,提问作者Wrongway Feldman

