自学内容网 自学内容网

VSCode使用Code Runner插件运行时,路径错误问题

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可成功运行程序:

在这里插入图片描述

参考


原文地址:https://blog.csdn.net/Xminyang/article/details/142757055

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!