python - 代码在空闲状态下工作,但在 VS Code 中出现错误

标签 python python-3.x visual-studio-code python-idle

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

代码在 IDLE 中工作正常,但在 Visual Studio Code 中出现错误

我添加了这一行 “打印(几)” 检查它是否在空闲状态下工作。它确实打印了它。

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'

最佳答案

正如其他人所指出的,问题在于 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)

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

关于python - 代码在空闲状态下工作,但在 VS Code 中出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57050964/

相关文章:

python - 在 python 中抛出 pdb 警告时如何查看函数内的变量?

Python 使用星号 (*)

python - Groupby 查找上一行之前的值

azure - 通过 VS Code 登录 Azure 失败,显示 "You appear to be offline"错误

Python: AttributeError: 'str' 对象没有属性 'decompressUnknownOriginalSize'

python - 是否有一些通用的数据结构来比较对象列表并在其中找到最相等的?

python - 子类化 Python str 类并与纯字符串进行字符串比较

python-3.x - Flask属性错误: module object has no attribute 'app'

java - 评估失败,因为线程未挂起

visual-studio-code - 在 Visual Studio Code 中添加断点