Python循环修改外部文件变量仅重启Shell窗口生效的问题及优化方案咨询
Hey there! Let's break down what's going on here and fix this properly 😊
The Root of the Problem
When you run your loop with change = gold + 1, that gold variable is a static copy stored in your program's memory from when you first imported test.py. Modifying the file doesn't automatically update this in-memory variable—so every iteration of the loop is using the same original gold value to calculate gold + 1. That's why no matter how many times you loop, the file only gets updated once to original_gold + 1.
Your temporary reload hack works, but the sleep(1) is totally unnecessary (file writes are synchronous, so the file is already saved by the time ovr finishes running). Plus, reloading the entire module is clunky and can cause side effects if test.py has other code.
Better Solutions
Step 1: Refactor the ovr Function
First, let's clean up your ovr function to make it more robust and readable:
def ovr(file, target, change): # Read the file content first with open(file, "r") as open_file: lines = open_file.readlines() # Find the line with our target variable target_index = None for idx, line in enumerate(lines): if target in line: target_index = idx break if target_index is None: raise ValueError(f"Couldn't find variable '{target}' in {file}") # Generate the updated line using f-strings (cleaner than concatenation) if isinstance(change, int): updated_line = f"{target} = {change}\n" else: updated_line = f"{target} = '{change}'\n" # Write the modified content back to the file with open(file, "w") as open_file: lines[target_index] = updated_line open_file.writelines(lines)
Key improvements here:
- Removed redundant
open_file.close()calls (thewithcontext manager handles this automatically) - Used
isinstance()instead oftype() ==for more flexible type checking - Added error handling for when the target variable isn't found
- Swapped messy string concatenation for readable f-strings
Step 2: Fetch the Latest Value Before Each Update
To fix the loop issue, we need to get the current value of gold from the file before each iteration. Let's add a helper function to do that:
def get_current_value(file, target): with open(file, "r") as f: for line in f: if target in line: # Split the line to extract the value part _, value_part = line.strip().split(" = ", maxsplit=1) # Handle both integer and string values cleaned_value = value_part.strip("'\"") try: return int(cleaned_value) except ValueError: return cleaned_value raise ValueError(f"Variable '{target}' not found in {file}")
Now your loop will work as expected:
for _ in range(5): current_gold = get_current_value("test.py", "gold") ovr(file="test.py", target="gold", change=current_gold + 1)
This way, every loop iteration grabs the latest gold value directly from the file, adds 1, and writes it back—no more stale in-memory variables!
Why This Works
Instead of relying on an imported variable that never updates, we're reading the file's current state every time we need to calculate the new value. This ensures each iteration builds on the previous update, so after 5 loops, gold will be 5 higher than its starting value.
内容的提问来源于stack exchange,提问作者Xour

