VS Code中Run Code按钮运行Python相对路径程序失败求助
相对路径在VS Code Run Code中失效的原因及解决方法
环境信息
- Windows 11
- Python 3.11.4
- VS Code
程序信息
程序路径:d:\Learning\Programming\python_work\File_Reader\file_reader.py
file_reader.py与File文件夹均位于File_Reader文件夹下,pi_digits.txt位于File文件夹中。初始代码使用相对路径:
file_path = 'File\\pi_digits.txt' with open(file_path) as file_object: contents = file_object.read() print(contents) #This program try to open the file:d:\Learning\Programming\python_work\File_Reader\File\pi_digits.txt #and print the numbers stored in this file
第一次尝试
在VS Code终端运行,当前工作目录为File_Reader:
PS D:\Learning\Programming\python_work\File_Reader> python file_reader.py
运行结果符合预期:
3.1415926535 8979323846 2643383279
第二次尝试
使用Run Code按钮(Ctrl+Alt+N)运行,报错找不到文件:
[Running] python -u "d:\Learning\Programming\python_work\File_Reader\file_reader.py" Traceback (most recent call last): File "d:\Learning\Programming\python_work\File_Reader\file_reader.py", line 2, in <module> with open(file_path) as file_object: ^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: 'File\\pi_digits.txt' [Done] exited with code=1 in 0.097 seconds
最后一次尝试
改用绝对路径后,两种运行方式均正常:
file_path = 'd:\\Learning\\Programming\\python_work\\File_Reader\\File\\pi_digits.txt' with open(file_path) as file_object: contents = file_object.read() print(contents)
原因分析
核心问题是两种运行方式的工作目录不一致:
- 终端运行时,你手动切换到了
File_Reader目录,此时程序的工作目录就是该文件夹,相对路径File\pi_digits.txt会被正确解析为d:\Learning\Programming\python_work\File_Reader\File\pi_digits.txt,与实际文件路径匹配。 - VS Code的Run Code按钮默认工作目录并非脚本所在的
File_Reader文件夹,而是VS Code当前打开的工作区根目录(比如你可能打开的是python_work作为工作区),或者系统默认路径。此时相对路径File\pi_digits.txt会被解析为工作区根目录下的File文件夹,而实际该文件夹在File_Reader子目录中,因此找不到文件。
解决方法
修改Run Code的默认工作目录:
打开VS Code设置,搜索Code-runner: Working Directory,将其设置为${fileDirname}。这样Run Code会自动以当前脚本所在的文件夹作为工作目录,相对路径即可正常识别。代码中动态构建路径:
通过Python的os模块获取脚本所在目录,再拼接目标文件路径,确保无论在哪运行都能找到文件:import os # 获取当前脚本的绝对路径所在目录 script_directory = os.path.dirname(os.path.abspath(__file__)) # 拼接目标文件路径 file_path = os.path.join(script_directory, 'File', 'pi_digits.txt') with open(file_path) as file_object: contents = file_object.read() print(contents)
内容的提问来源于stack exchange,提问作者zyyHelios
相关产品推荐
相关产品推荐

