如何在VS Code中使用Python永久保存数据?
Absolutely! There are several straightforward ways to persist your data between Python development sessions in VS Code, so you can skip re-running all your code every time. Let’s go through the most practical methods tailored to different data types:
If you’re working with custom objects, nested dictionaries, or things like trained ML models, Pickle (Python’s built-in module) is perfect—it saves your data exactly as it exists in memory.
To save your data:
import pickle # Assume `your_data` is the object you want to save with open("saved_data.pkl", "wb") as f: pickle.dump(your_data, f)
To load it later in a new session:
import pickle with open("saved_data.pkl", "rb") as f: loaded_data = pickle.load(f)
⚠️ A quick note: Only load pickle files you trust—malicious pickle data can execute code when loaded.
If your data is made of simple types (dictionaries, lists, strings, numbers), JSON is great because it’s plain text—you can even open and edit it in VS Code directly.
Save with JSON:
import json # `your_data` should be JSON-serializable (no custom objects!) with open("saved_data.json", "w") as f: json.dump(your_data, f, indent=4) # Indent makes it readable
Load it back:
import json with open("saved_data.json", "r") as f: loaded_data = json.load(f)
For tabular or relational data (like you’d store in a spreadsheet), SQLite is a built-in, file-based database—no server setup required. It’s ideal if your data needs querying or updating over time.
Example workflow:
import sqlite3 # Connect to a database file (creates it if it doesn't exist) conn = sqlite3.connect("my_database.db") cursor = conn.cursor() # Create a table (run once) cursor.execute(""" CREATE TABLE IF NOT EXISTS my_data ( id INTEGER PRIMARY KEY, value TEXT, count INTEGER ) """) # Insert data cursor.execute("INSERT INTO my_data (value, count) VALUES (?, ?)", ("example", 5)) conn.commit() # Load data in a new session conn = sqlite3.connect("my_database.db") cursor = conn.cursor() cursor.execute("SELECT * FROM my_data") loaded_data = cursor.fetchall() conn.close()
If you’re using pandas for data analysis, Feather or Parquet are optimized for speed and storage efficiency. Feather is great for quick I/O, while Parquet is better for compressing large datasets.
Using Feather:
import pandas as pd # Save a DataFrame df.to_feather("saved_data.feather") # Load it later loaded_df = pd.read_feather("saved_data.feather")
Pro Tip for VS Code
To make this even smoother, create a small utility script (e.g., data_utils.py) in your workspace with reusable save/load functions:
# data_utils.py import pickle def save_data(data, filename): with open(filename, "wb") as f: pickle.dump(data, f) def load_data(filename): with open(filename, "rb") as f: return pickle.load(f)
Then in your main code, just import and call:
from data_utils import save_data, load_data # After generating data save_data(your_data, "my_data.pkl") # In a new session your_data = load_data("my_data.pkl")
Pick the method that fits your data type, and you’ll cut down on repetitive code runs in no time!
内容的提问来源于stack exchange,提问作者thequadge

