【问题标题】:DJANGO - FileNotFoundError: [Errno 2] No such file or directory: '' when trying to acess a fileDJANGO - FileNotFoundError: [Errno 2] No such file or directory: '' 尝试访问文件时
【发布时间】:2020-11-09 19:25:09
【问题描述】:

我正在从一个脚本访问一个函数,该脚本基本上读取一个 JSON 文件并返回一些值。

  • main/randomgenerator/generatorran.py
def getName():
    with open('names.json','r') as names:
             ....
  • 手动执行时功能正常(python generatorran.py)

我目前正在导入该函数并在创建模型时调用它。

  • main/models.py
from main.randomgenerator import generatorran


class myModel:
    ...
    model_name = models.CharField(max_length=100,default=generatorran.getName())
  • 应用迁移时会抛出错误

    FileNotFoundError: [Errno 2] No such file or directory: '' when trying to acess a file

当我在 models.py 中移动函数时也会发生同样的情况

还有其他方法可以从外部文件中读取数据吗,我是否遗漏了什么?

【问题讨论】:

  • 尝试使用names.json的绝对路径而不是相对路径。
  • 绝对路径确实有效

标签: python json python-3.x django file-not-found


【解决方案1】:

Django 找不到该文件,因为当前工作目录在其他地方

要检查这一点,请将其添加到您的 python 文件中

print os.getcwd()

正如 Vishal Singh 在他的评论中所说,使用绝对路径而不是相对路径

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2012-08-25
    • 2019-10-14
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多