How to import text files in web app?

My web app tries to call:



inFile = open(WORDLIST_FILENAME, 'r', 0)

I have words.txt uploaded to my mysite directory, how do I point to it?

I also attempt to call:

import random

import string

Can I do this with flask or do I need to do something else first?



Two things I can think of immediately:

  • (1) Try making your path absolute, so '/home/JackRabuck/django_project/words.txt'
  • (2) Make sure you're reloaded your webapp from the 'web' tab of the Dashboard



Hi JackRabuck,

rcs1000 has it I think. "words.txt" needs to be in the current working directory of the web server process. You can see what this is by doing something like

import os
return os.getcwd()

In your flask view code. Once you find out what the current working directory is then you could supply a relative path. Which might look like "django_project/words.txt". But it might just be easier to provide an absolute path. Like in rcs1000's example.

I would strongly suggest always trying to use absolute paths in any code, especially web-based - relative filenames can cause all sorts of sticky issues waiting to bite you when you move your code to another platform or environment.

In cases where you have no control over the path (e.g. the user can specify it in configuration), I suggest converting it to an absolute one with os.path.abspath() as soon as you can so at least the rest of your code can deal with it as an absolute path. That way if you find you have a problem, the amount of code you need to address is minimal.

one trick we often use to have a solid, non-controversial way of finding your way around the file system is to use __file__, because that always tells you the path to the file for the current bit of source code, so eg:

this_directory = os.path.abspath(os.path.dirname(__file__))
parent_directory = os.path.split(this_directory)[0]
parent_directory = os.path.abspath(os.path.join(this_directory, '..'))
# etc, etc

well done