-1

I have been working on a Flask project. But I have run into an issue.
To understand my problem properly, you have to take a look at my folder structure.

enter image description here



enter image description here



I want to access the './static/data/wordlist.txt' in my models.py file using url_for syntax.
This is what I have written: url_for('static', filename='data/wordlist.txt').

But flask is giving me an error saying: FileNotFoundError: [Errno 2] No such file or directory: '/static/data/wordlist.txt'

Any help as to what I should do would be great!!

davidism
  • 121,510
  • 29
  • 395
  • 339
Sobhan Bose
  • 114
  • 9
  • what is the purpose(what are you going to use it for) of the URL that is being built – jaswanth Nov 16 '20 at 13:44
  • I am making a url shortener. wordlist.txt contains a number of random words from which the program chooses a word randomly and add it to the database. For this purpose, I want to access wordlist.txt inside models.py – Sobhan Bose Nov 16 '20 at 13:54
  • Please make a note that I have already tried to do this using `with open("./static/data/wordlist.txt) as file`. But it is giving me the same error. – Sobhan Bose Nov 16 '20 at 13:56
  • may be you should use absolute path, `dir_name = os.path.dirname(os.path.abspath(__file__))` and use `wordlist_path = os.path.join(dir_name, "static/data/wordlist.txt")` – jaswanth Nov 16 '20 at 13:58
  • My aim is to host this in an online server. So giving absolute path is not an option for me. I have to use url_for. – Sobhan Bose Nov 16 '20 at 14:00
  • I have updated my comment please have a look – jaswanth Nov 16 '20 at 14:01
  • I have another doubt! Will this work when I deploy it to an online server like Heroku? – Sobhan Bose Nov 16 '20 at 14:03
  • yes as long as the directory structure remains intact as above – jaswanth Nov 16 '20 at 14:04

1 Answers1

0

Use app.url_root to get a path relative to your code.

wordlist_path = os.path.join(app.root_path, "static/data/wordlist.txt")

with open(wordlist_path) as f:
    ...
davidism
  • 121,510
  • 29
  • 395
  • 339
jaswanth
  • 515
  • 2
  • 7