python - 代码在空闲状态下工作,但在 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'
解决方案
正如其他人指出的那样,问题在于 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)
此代码应在打开文件之前放置。
推荐阅读
- nginx - NGINX 控制器 - 仅在服务内部删除文件路径,然后将其附加回来
- python - 二进制变量集的logit优化方法
- html - Drupal 8,Webform 模块:发送带有纯文本 mime/alternative 的 html 邮件
- imagemagick - 在Sharp js中是否有类似imagemagick OilPaint过滤器的功能来平滑边缘?
- assembly - 满足条件时计算数组和的 ASM 程序
- python - scala 在构造集合时比 python 慢
- c++ - 使用 VS 2008 c++ 使用动态变量更新 ODBC
- typo3 - TYPO3 流体模板变量
- javascript - 如何在 JavaScript 中获取历史第一个不同的 url?
- c++ - 变量优先队列