VS Code中Python文件移至子目录后读写路径异常求助
问题:Python文件读写路径与脚本所在目录不一致的解决方法
问题背景
- VS Code工作区设置为
/Users/xxxx/Documents/900. PYTHON/# VS Code/Workspace/ - 原本
main.py与exercise_register.csv都在该工作区根目录,读写文件正常 - 将两个文件一同移至子目录
workouts/后出现以下问题:- 读取文件时触发
FileNotFoundError,提示找不到exercise_register.csv - 写入文件时,新文件被创建在原工作区根目录,而非
workouts/子目录
- 读取文件时触发
读取时的错误信息
Exception has occurred: FileNotFoundError [Errno 2] No such file or directory: 'exercise_register.csv' File "/Users/xxxx/Documents/900. PYTHON/# VS Code/Workspace/workouts/main.py", line 51, in review_register with open("exercise_register.csv", "r") as file: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
当前写入文件的代码
with open("exercise_register.csv", "w") as file: for line in data: file.write(line)
解决方案
核心思路是基于脚本文件所在目录构建文件路径,而非依赖VS Code的工作目录。以下两种方法均可实现:
方法1:使用os模块(兼容所有Python版本)
利用__file__变量获取当前脚本的绝对路径,再拼接目标文件路径:
import os # 获取当前脚本所在目录的绝对路径 script_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接csv文件的完整路径 csv_file_path = os.path.join(script_dir, "exercise_register.csv") # 读取文件 with open(csv_file_path, "r") as file: # 执行读取逻辑 # 写入文件 with open(csv_file_path, "w") as file: for line in data: file.write(line)
方法2:使用pathlib(Python 3.4+ 推荐)
pathlib提供更简洁的面向对象路径操作:
from pathlib import Path # 获取当前脚本所在目录的绝对路径 script_dir = Path(__file__).parent.resolve() # 拼接csv文件路径(支持/运算符) csv_file_path = script_dir / "exercise_register.csv" # 读取文件 with open(csv_file_path, "r") as file: # 执行读取逻辑 # 写入文件 with open(csv_file_path, "w") as file: for line in data: file.write(line)
原理说明
当使用相对路径(如"exercise_register.csv")时,Python会以当前工作目录(即VS Code设置的工作区根目录)为基准查找文件,而非脚本所在的子目录。通过__file__或pathlib获取脚本所在目录后,就能确保文件操作始终基于脚本的实际位置,不受工作目录变化影响。
内容的提问来源于stack exchange,提问作者PLR06157
相关产品推荐
相关产品推荐

