代码在空闲状态下工作,但在 VS 代码中出错

Code works in Idle but getting an error in VS Code

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

代码在 IDLE 中运行良好,但在 Visual Studio 代码

中出现错误

我添加了这行 "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'

给出完整路径,它应该运行 来自任何地方

假设您正在使用 linux 系统并且您的文件位于主文件夹中的 xyz 文件夹中

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

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

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

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

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

import os

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

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

假设文本文件与 python 文件位于同一目录中,您应该能够执行以下操作:

import random
import os

file_name = "StatesANC.txt"
basedir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(basedir, file_name)

infile=open(file_path,"r")
print("few")

将绝对路径放在 open(r"/rootpath/subpath/StatesANC.txt","r") 上,可能文件 StatesANC.txt 不在路径 f:/SKKU/study/ISS3178 - Python/11/ 上。