VS Code中Python文件保存时自动创建文件夹的解决方法咨询
解决每次保存Python文件就自动创建文件夹的问题
一、先改代码:避免重复创建文件夹
你的代码里os.makedirs每次运行都会强制创建文件夹,加上判断或者参数就能解决重复创建的问题,同时优化路径拼接的写法:
import os # 补充你可能用到的时间变量定义(如果还没加的话) from datetime import datetime current_date = datetime.now().strftime("%Y-%m-%d") current_datetime = datetime.now().strftime("%H-%M-%S") project_dir_path = os.getcwd() # 不用手动加/,os.path.join会自动处理路径分隔符,跨系统更友好 reports_dir_path = os.path.join(project_dir_path, "Reports") current_date_report_dir_path = os.path.join(reports_dir_path, current_date) current_datetime_report_dir_path = os.path.join(current_date_report_dir_path, current_datetime) # 两种可选写法二选一: # 写法1:先判断文件夹是否存在,不存在再创建 if not os.path.exists(current_datetime_report_dir_path): os.makedirs(current_datetime_report_dir_path) # 写法2(更简洁,Python3.2+支持):允许文件夹已存在,不报错 # os.makedirs(current_datetime_report_dir_path, exist_ok=True)
二、检查VS Code设置:阻止保存时自动运行脚本
每次保存就触发创建,说明你的VS Code可能开了保存自动执行Python文件的功能,按以下步骤检查:
- 打开VS Code设置(快捷键
Ctrl+,或Cmd+,) - 搜索
python.runOnSave,如果值是true,改成false - 如果你装了Code Runner扩展,打开扩展设置,找到「Run on Save」相关选项,把自动运行关掉
内容的提问来源于stack exchange,提问作者AbdulQASDET
相关产品推荐
相关产品推荐

