1. 问题介绍
由于Code Runner插件的工作目录与文件执行目录不同,而导致路径错误!
示例演示:
创建根目录test-dir,然后在里面分别创建两个目录code和data,分别存放Python程序read_file.py和输入数据input.txt
read_file.py内容为:
def read_and_write_file(input_file_path, output_file_path):
try:
with open(input_file_path, 'r', encoding='utf-8') as file:
content = file.read()
output_content = f"I get {content}"
with open(output_file_path, 'w', encoding='utf-8') as file:
file.write(output_content)
print(f"Content from {input_file_path} has been written to {output_file_path}.")
except FileNotFoundError:
print(f"The file at {input_file_path} was not found.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
input_file_path = '../data/input.txt'
output_file_path = '../data/output.txt'
read_and_write_file(input_file_path, output_file_path)
input.txt内容为:
Hello, World.
使用Code Runner运行程序时,报错The file at ../data/input.txt was not found.
,如下图所示:
2. 解决方案
打开VSCode 设置settings
,搜索file directory
,然后在勾选
Code-runner: File Directory As Cwd
再次使用Code Runner可成功运行程序:
参考
- VSCode中,Code Runner插件运行单个文件,文件中的相对路径报错异常