How to read csv file into django project?

80 Views Asked by At

I'm using csv(txt) file to make graphs, but Django doesn't want to find it. So I can't understand, where should I create a file.

def get_plot():
    df = pd.read_csv('jobibi.txt', sep=',', encoding='utf-8')

And the output on the web page:

FileNotFoundError at /analytics/
[Errno 2] No such file or directory: 'jobibi.txt'

I tried to change the directory, but it didn't work

1

There are 1 best solutions below

0
On

You need to provide the full path to the file you want to open.
It is generally considered to be a bad idea to hardcode the path of the file in the function call.

You can import the path of your project from your settings.py and go from there.

from *your_project_folder*.settings import BASE_DIR

You can navigate this path like this:

# move deeper into the path tree
my_deeper_path = BASE_DIR / 'my_directory'

# move out one level
my_shallower_path = BASE_DIR.parent

For more detailed information on how to navigate the paths in python - pathlib docs

It should look something like this. Now you should be able to read your file.

from *your_project_folder*.settings import BASE_DIR

def get_plot():
    file_path = BASE_DIR / 'analytics_app' / 'jobibi.txt'
    df = pd.read_csv(file_path, sep=',', encoding='utf-8')

If your files are always in the same directory i recommend adding a dedicated variable in your settings.py

MY_CSV_PATH = BASE_DIR / 'my_permanent_directory/'

Then you only need to import MY_CSV_PATH and add the filename to it.

I hope this helped. Let me know if you are still having problems with it.