Python将用户输入存入JSON适配Pandas分析及代码优化咨询
Hey there! Let’s tackle your Python questions one by one, and we’ll clean up that repetitive code while we’re at it.
The built-in json module is your go-to tool here—it makes converting Python data to JSON (and vice versa) straightforward. Here’s a simple, safe workflow:
- Import the
jsonmodule. - Collect all user inputs into a Python dictionary (since dictionaries map directly to JSON objects).
- Use a
withstatement to open your file (this handles closing the file automatically, so you don’t have to worry about leaks). - Write the dictionary to the file using
json.dump()(for single entries) or append multiple entries in JSON Lines format (each entry on a new line, perfect for later analysis).
Example for a single entry (overwrites the file):
import json # Gather input into a structured dictionary user_data = { "Name": input("Name: "), "Date": input("Enter a date in YYYY-MM-DD format: "), "Hours": input("Hours: "), "Rate": input("Rate: "), "Topic": input("To... ") } # Write to JSON file with pretty formatting with open("user_logs.json", "w") as f: json.dump(user_data, f, indent=4)
Example for appending multiple entries (JSON Lines):
import json user_data = { "Name": input("Name: "), "Date": input("Enter a date in YYYY-MM-DD format: "), "Hours": input("Hours: "), "Rate": input("Rate: "), "Topic": input("To... ") } # Append to the file without overwriting existing content with open("user_logs.jsonl", "a") as f: json.dump(user_data, f) f.write("\n") # Separate entries with a newline
Absolutely—this is actually the ideal structure for Pandas! JSON objects (which match Python dictionaries) translate directly into Pandas DataFrames, where each key becomes a column.
If you use the JSON Lines format from the example above, loading into Pandas takes one line:
import pandas as pd # Load the JSON Lines file into a DataFrame df = pd.read_json("user_logs.jsonl", lines=True) print(df)
This gives you a clean, tabular dataset ready for filtering, sorting, or calculating totals (like total hours worked per user). Even if you store all entries in a single JSON array (a list of dictionaries), Pandas can read that too with pd.read_json("user_logs.json").
Your current code has repetitive open() calls and unstructured text storage—we can fix both easily. Here’s a streamlined version that’s scalable and maintainable:
Key improvements:
- Dynamic file handling: Use the user’s input name to open the correct file automatically (no more hardcoding filenames).
- Structured storage: Save data as JSON instead of raw text, making it usable for Pandas later.
Simplified code:
import json # Collect all input fields except name first user_input = { "Date": input('Enter a date in YYYY-MM-DD format: '), "Hours": input("Hours: "), "Rate": input("Rate: "), "Topic": input("To... ") } # Get the name to target the right file (lowercase to avoid case mismatches) name = input("Name: ").strip().lower() filename = f"{name}.json" # Append the structured entry to the user's file with open(filename, "a") as f: json.dump(user_input, f) f.write("\n") print(f"Data saved to {filename} successfully!")
Loading a user’s data into Pandas later:
import pandas as pd df_jessica = pd.read_json("jessica.json", lines=True) print(df_jessica)
This code scales automatically—you don’t need to add new open() lines for every new user, and the structured JSON makes analysis trivial.
内容的提问来源于stack exchange,提问作者Penny Pang

