【问题标题】:FileNotFoundError in Python Visul StudioPython Visual Studio 中的 FileNotFoundError
【发布时间】:2022-02-12 08:56:06
【问题描述】:

当我尝试运行我的 python 项目代码时,我得到了这个

with open("config.json", "r") as f:

引发异常:

FileNotFoundError: [Errno 2] No such file or directory: 'config.json'

对此有什么解决方案?

here is a screenshot of the code and everything.

【问题讨论】:

  • config.json 文件需要与您的 python 代码位于同一文件夹中。你能告诉我们json文件和你的python代码现在是如何定位的吗?
  • 尝试使用绝对全名而不是相对名称。
  • @SangkeunPark 这里是代码截图i.stack.imgur.com/yMy7y.png
  • @LeiYang 你能解释一下吗?
  • open("C:/some path/config.json")

标签: python filenotfounderror


【解决方案1】:

如果您不使用完整路径,文件 config.jason 需要位于您当前的工作目录中才能通过 open 找到。你的 cwd 可能是你启动 python 的地方。检查做

    import os
    print(os.getcwd())

您最简单的解决方案可能是使用文件的完整路径名。

【讨论】:

    【解决方案2】:

    如 IDE 的屏幕截图所示,您应该准确指出 .json 文件的位置。现在json文件和python代码不在同一个文件夹里了。

    仅供参考,有两种类型的路径,绝对路径和相对路径。请看https://www.kite.com/python/answers/how-to-find-the-absolute-and-relative-path-of-a-file-in-pythonhttps://www.kite.com/python/answers/how-to-find-the-absolute-and-relative-path-of-a-file-in-python

    with open("/file program/config.json", "r") as f
        content = f.read()
        # do something
    

    或者,将config.json文件移出到python代码所在的文件夹。

    【讨论】:

    • 我按照你说的将 .json 文件放在与 python 代码所在的文件夹相同的文件夹中,就像这样 imgur.com/a/9ulb9OU 现在我在终端中遇到了这个问题 imgur.com/a/W9Te01U
    • bot.py 在哪里?图片显示 C:\Users\97154\Desktop\EinsteinBot-master (1)\EinsteinBot-master 处没有bot.py
    • 我这里有..imgur.com/a/9ulb9OU ...那有什么问题?
    • @tareq 现在最好将这两个文件放在同一个文件夹中。然后,您必须在 C:\Users\97154\Desktop\EinsteinBot-master (1)\EinsteinBot-master\file program 处运行 bot.py,因为您将 bot.py 移动到该文件夹​​。
    • 是的,我做到了,我必须这样做 cd "filename" 我在这里做到了,现在我遇到了这个 cogs 问题imgur.com/a/q0Q47Ec(我将“EinsteinBot-master”文件名更改为“chegg”)这是 cogs imgur.com/a/O9qrAg2 的代码
    猜你喜欢
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多