You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何永久修改另一个.py文件中的列表并保存更改?

How to Permanently Modify list_things in list.py via GUI

Hey there! Let's tackle this problem where you want to add or insert elements to list_things in list.py using a GUI in main.py, and make sure those changes stick even after restarting your program. I'll walk you through two approaches—one that directly modifies list.py as you requested, and a more robust alternative that's better for dynamic data storage.

Approach 1: Directly Modify list.py (Exact Request)

This method reads the current list_things from list.py, updates it via your GUI, then rewrites the entire file with the new list.

Step 1: Your Initial list.py

Make sure your list.py starts with the list definition like this:

list_things = ["john", "albert", "Martin", "Suzzy"]

Step 2: main.py Code with GUI

Here's a complete example using Tkinter (Python's built-in GUI toolkit) that lets you add elements and saves changes to list.py:

import tkinter as tk

def load_list():
    """Load the current list_things from list.py"""
    with open("list.py", "r") as file:
        content = file.read()
    
    # Execute the content to extract list_things (safe for your own code)
    local_vars = {}
    exec(content, globals(), local_vars)
    return local_vars["list_things"]

def save_list(updated_list):
    """Rewrite list.py with the updated list_things"""
    # Use repr() to ensure strings are properly quoted/escaped
    new_content = f'list_things = {repr(updated_list)}\n'
    with open("list.py", "w") as file:
        file.write(new_content)

def add_element():
    """Handle adding a new element via the GUI"""
    new_item = entry_input.get().strip()
    if not new_item:
        return  # Ignore empty input
    
    # Get current list, add the new item, save
    current_list = load_list()
    current_list.append(new_item)  # Use current_list.insert(index, new_item) to insert at specific position
    save_list(current_list)
    
    # Clear input and refresh the displayed list
    entry_input.delete(0, tk.END)
    refresh_list_display()

def refresh_list_display():
    """Update the listbox to show the latest list_things"""
    list_box.delete(0, tk.END)
    for item in load_list():
        list_box.insert(tk.END, item)

# Set up the GUI window
root = tk.Tk()
root.title("Modify list_things")

# Input field and add button
entry_input = tk.Entry(root, width=35)
entry_input.pack(pady=10)

btn_add = tk.Button(root, text="Add Element", command=add_element)
btn_add.pack(pady=5)

# Listbox to display current items
list_box = tk.Listbox(root, width=35, height=8)
list_box.pack(pady=10)

# Load initial list when the app starts
refresh_list_display()

root.mainloop()

Important Notes:

  • The exec() function is safe here because you're executing your own list.py code—avoid using this with untrusted files.
  • Using repr() ensures that elements with special characters (like quotes) are properly formatted in the saved list.

Modifying a code file (list.py) for dynamic data storage isn't ideal—it mixes code and data, and can lead to accidental syntax errors if something goes wrong. A better practice is to use a dedicated data file like JSON.

Step 1: Create data.json

Start with this JSON file (it will hold your list):

["john", "albert", "Martin", "Suzzy"]

Step 2: Updated main.py Code

This version reads/writes from data.json instead of modifying list.py:

import tkinter as tk
import json

def load_list():
    """Load the list from data.json (fallback to initial list if file doesn't exist)"""
    try:
        with open("data.json", "r") as file:
            return json.load(file)
    except FileNotFoundError:
        return ["john", "albert", "Martin", "Suzzy"]

def save_list(updated_list):
    """Save the updated list to data.json"""
    with open("data.json", "w") as file:
        json.dump(updated_list, file, indent=2)

# Rest of the GUI code is identical to Approach 1—just reuse add_element, refresh_list_display, etc.

Why This Is Better:

  • Separation of concerns: Code stays in .py files, data stays in a dedicated storage file.
  • Safety: No risk of breaking your list.py code with invalid syntax.
  • Flexibility: JSON works well for more complex data structures if you need to expand later.

Either approach will let you make permanent changes that persist across program restarts. Pick the first one if you strictly need to modify list.py, or the second for a more maintainable setup.

内容的提问来源于stack exchange,提问作者tech_cartel

火山引擎 最新活动