Windows环境下写入vars.py遇PermissionError权限问题求助
解决Windows下Python写入文件PermissionError及VS Code文件不更新问题
问题核心
Windows环境中,配置Discord机器人的tkinter脚本写入vars.py时抛出PermissionError: [Errno 13] Permission denied: 'vars.py',同时VS Code运行程序无报错但文件未更新。
解决方案
1. 排查文件占用情况
- 关闭所有打开
vars.py的程序(包括VS Code中的对应标签页),避免文件被进程锁定。 - 重启Python解释器,确保之前的程序进程已完全退出。
2. 确保写入路径正确(关键)
Windows下Python运行的工作目录可能和脚本所在目录不一致,导致写入错误路径引发权限问题。修改代码使用绝对路径写入:
import tkinter as tk from tkinter import ttk from tkinter import messagebox import os def write_to_file(file_path, text): # 获取当前脚本所在的绝对目录 script_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接目标文件的绝对路径 full_file_path = os.path.join(script_dir, file_path) with open(full_file_path, 'w') as file: file.write(text) def submit(): vc_id = vc_id_entry.get() sender_token = sender_token_entry.get() receiver_token = receiver_token_entry.get() write_to_file("vars.py", f"vc_id = {vc_id}\ns_token = \"{sender_token}\"\nr_token = \"{receiver_token}\"\nsetup = True") messagebox.showinfo("Setup Done", "You may now close the window") # Create main window root = tk.Tk() root.title("Setup") # Create labels and entry boxes vc_id_label = ttk.Label(root, text="VC ID:") vc_id_label.grid(row=0, column=0, padx=10, pady=10, sticky=tk.W) vc_id_entry = ttk.Entry(root, width=40) vc_id_entry.grid(row=0, column=1, padx=10, pady=10) sender_token_label = ttk.Label(root, text="Sender Token:") sender_token_label.grid(row=1, column=0, padx=10, pady=10, sticky=tk.W) sender_token_entry = ttk.Entry(root, width=40) sender_token_entry.grid(row=1, column=1, padx=10, pady=10) receiver_token_label = ttk.Label(root, text="Receiver Token:") receiver_token_label.grid(row=2, column=0, padx=10, pady=10, sticky=tk.W) receiver_token_entry = ttk.Entry(root, width=40) receiver_token_entry.grid(row=2, column=1, padx=10, pady=10) # Submit button submit_button = ttk.Button(root, text="Submit", command=submit) submit_button.grid(row=3, columnspan=2, pady=10) # Start GUI root.mainloop()
3. 检查目录写入权限
- 右键点击脚本所在文件夹,选择属性 > 安全,确认当前登录用户拥有写入权限。若缺失,点击“编辑”添加写入权限。
- 临时排查:右键VS Code选择以管理员身份运行,再执行程序,若能正常写入则说明是目录权限问题。
4. 解决VS Code文件不更新问题
- 重载VS Code窗口:按下
Ctrl+Shift+P,输入Reload Window执行,清除文件缓存。 - 配置运行工作目录:在VS Code的“运行和调试”面板中,编辑
launch.json,添加"cwd": "${fileDirname}",确保程序运行时的工作目录为脚本所在目录:{ "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "cwd": "${fileDirname}" } ] } - 开启自动保存:点击VS Code右下角的“自动保存”按钮,确保文件修改后实时同步。
内容的提问来源于stack exchange,提问作者Suberbmuffin
相关产品推荐
相关产品推荐

