如何按条件将JSON字典导出至多个文件?学生单文件存储需求问询
How to Save/Update Individual JSON Files for Each Student
Got it, let's adjust your code so every student gets their own JSON file that updates with new entries each time you input data for them. Here's a complete, working solution:
import json import os def save_student_data(): # Get student name and sanitize filename to avoid filesystem issues student_name = input("Name: ").strip() filename = f"{student_name.replace(' ', '_').lower()}.json" # Collect the new entry details new_entry = { 'date': input('Enter a date in YYYY-MM-DD format: ').strip(), 'hours': input("Hours: ").strip() } # Load existing data if the student's file already exists if os.path.exists(filename): try: with open(filename, 'r') as file: student_records = json.load(file) # Ensure we're working with a list (in case the file had invalid data) if not isinstance(student_records, list): student_records = [] except json.JSONDecodeError: print(f"Warning: {filename} is corrupted. Starting fresh with new data.") student_records = [] else: # No existing file, create a new list for the student's records student_records = [] # Add the new entry to the student's records student_records.append(new_entry) # Save the updated records back to the JSON file with open(filename, 'w') as file: json.dump(student_records, file, indent=4) # Indent makes the file human-readable print(f"Data saved successfully to {filename}!") # Run the function when the script is executed if __name__ == "__main__": save_student_data()
Key Features Explained:
- Individual Files: Each student gets a unique JSON file named after their name (e.g.,
penny_pang.jsonfor "Penny Pang")—we replace spaces with underscores and use lowercase to avoid cross-OS filesystem issues. - Update Existing Records: If the student's file already exists, we load all their previous entries and append the new one instead of overwriting everything.
- Error Handling: We handle cases where the JSON file might be corrupted, so the script doesn't crash and starts fresh for that student if needed.
- Readable Output: The
indent=4parameter injson.dumpformats the JSON file with proper spacing, making it easy to read manually.
Example Workflow:
- Run the script, enter "Penny Pang" as the name, then a date and hours. A
penny_pang.jsonfile is created with:[ { "date": "2024-05-20", "hours": "3" } ] - Run the script again, enter "Penny Pang" once more, add new date and hours. The file updates to:
[ { "date": "2024-05-20", "hours": "3" }, { "date": "2024-05-21", "hours": "5" } ]
内容的提问来源于stack exchange,提问作者Penny Pang
相关产品推荐
相关产品推荐

