所以我正在编写需要导入文件的代码。 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/