Python 3.6.4(Spyder 3.2.7) CSV变量存储权限问题及功能实现求助
Hey there! Let's tackle your problem from two key angles first: resolving that frustrating PermissionError on line 18, then setting up the CSV-based state persistence you need (appending variable updates and resuming progress when your script restarts).
First: Fix the PermissionError: [Errno 13]
This error almost always comes down to one of three simple issues—let's check them in order:
- The CSV file is open in another program: If you have
testcsv.csvopen in Excel, Notepad, or any other app, Python can't write to it. Close the file entirely, then re-run your script. - No write permissions for the file's directory: Avoid saving the CSV to system-protected folders (like
C:\Windowsor/root). Move it to a user-owned directory (e.g., your Documents folder) or adjust the directory's permissions to allow writes. - File is marked as read-only: Right-click the CSV file, open Properties, and uncheck the "Read-only" box if it's selected.
Once you've ruled these out, the permission error should vanish. Now let's build the state persistence logic you need.
Second: Append Variables to CSV on Update
To safely add new variable data to your CSV every time values change, use Python's built-in csv module with a context manager (with statement)—this ensures the file is properly closed after writing, preventing resource locks.
Here's a reusable function for appending rows:
import csv def append_to_csv(file_path, data_row): # 'a' = append mode; newline='' fixes cross-platform line ending issues with open(file_path, 'a', newline='', encoding='utf-8') as csv_file: writer = csv.writer(csv_file) writer.writerow(data_row) # Writes your variable set as a single row # Example usage: If your updated variables are name, age, status updated_vars = ["John", 30, "Active"] append_to_csv("testcsv.csv", updated_vars)
If you prefer working with named fields (easier to track later), use DictWriter instead:
def append_dict_to_csv(file_path, data_dict): field_names = ["Name", "Age", "Status"] with open(file_path, 'a', newline='', encoding='utf-8') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=field_names) # Write header only if the file is empty if csv_file.tell() == 0: writer.writeheader() writer.writerow(data_dict) # Example usage append_dict_to_csv("testcsv.csv", {"Name": "John", "Age": 30, "Status": "Active"})
Third: Resume State from CSV on Script Restart
To pick up where you left off, read the last row of the CSV when your script starts—this gives you the most recent variable values.
Here's a function to fetch the latest state:
def get_latest_state(file_path): try: with open(file_path, 'r', encoding='utf-8') as csv_file: reader = csv.reader(csv_file) rows = list(reader) if rows: # Get the last row (skip header if you have one—adjust index if needed) latest_row = rows[-1] # Convert values to the correct data types (e.g., string to int) name, age, status = latest_row[0], int(latest_row[1]), latest_row[2] return name, age, status else: # Return default values if file is empty return "DefaultUser", 0, "Inactive" except FileNotFoundError: # If file doesn't exist, create it and return defaults with open(file_path, 'w', newline='', encoding='utf-8') as csv_file: writer = csv.writer(csv_file) writer.writerow(["Name", "Age", "Status"]) # Optional header return "DefaultUser", 0, "Inactive"
Putting It All Together
Your script will now start by loading the latest state, update variables as needed, and append changes to the CSV:
CSV_PATH = "testcsv.csv" # Load saved state on startup current_name, current_age, current_status = get_latest_state(CSV_PATH) print(f"Resuming with state: Name={current_name}, Age={current_age}, Status={current_status}") # Simulate variable update during script run current_age += 1 current_status = "Active" # Save updated state to CSV append_to_csv(CSV_PATH, [current_name, current_age, current_status]) print(f"Updated state saved: Age is now {current_age}")
A quick note for Spyder users: Make sure you're not running multiple instances of the script—this can also cause file locks. Use the "Stop" button to kill any previous runs before starting a new one.
内容的提问来源于stack exchange,提问作者Goulouh Anwar




