简体   繁体   中英

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

I'm accessing a function from a script that basically reads a JSON file and returns some value.

  • main/randomgenerator/generatorran.py
def getName():
    with open('names.json','r') as names:
             ....
  • The function works normally when executing it manually ( python generatorran.py )

I'm currently importing that function and calling it when creating a model.

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


class myModel:
    ...
    model_name = models.CharField(max_length=100,default=generatorran.getName())
  • When applying migrations it throws an error

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

Is there another way to read data from external files,am I missing something?

Django cannot find the file because the current working directory is somewhere else

to check this out add this in your python file

print os.getcwd()

as Vishal Singh said in his comment use an absolute path instead of the relative one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM