首页 > 解决方案 > 代码在空闲状态下工作,但在 VS Code 中出现错误

问题描述

所以我正在编写一个需要导入文件的代码。python代码文件和我需要导入的文件都在同一个目录中,因此我没有指定整个路径。

该代码在 IDLE 中运行良好,但在 Visual Studio Code 中出现错误

我添加了“print(few)”行来检查它是否在 IDLE 中工作。它确实打印它。

import random
infile=open("StatesANC.txt","r")
print("few")

我在 Visual Studio 中得到的错误如下:-

Traceback (most recent call last):
File "f:/SKKU/study/ISS3178 - Python/11/Lab Assignment 11.py", line 2, in <module>
infile=open("StatesANC.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'StatesANC.txt'

标签: pythonpython-3.xvisual-studio-codepython-idle

解决方案


正如其他人指出的那样,问题在于 IDLE 和 Visual Studio Code 的默认工作目录可能不同。

测试这一点的一种方法是在脚本的开头包含以下内容:

import os
cwd = os.getcwd()
print(cwd)

如果确实如此,您可以将工作目录更改为脚本之一(其文件路径存储在特殊变量中__file__):

import os

script_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_path)

此代码应在打开文件之前放置。


推荐阅读