简体   繁体   中英

Referencing file in Django views.py

I am building a Django web interface (overkill - I know!) for a few small python functions. One of these transforms a txt file stored in Django root. Well it aims to.

I have the following setup in a few places:

with open('file.csv','r') as source:
...

However, without setting the entire directory on my machine (eg /home/...), it cannot find the file. I have tried putting this in the Static directory (as ideally I would like people to be able to download the file at a later stage) but same problem.

How do you work with files within Django? What is best practice to solve the above allowing someone to download it later?

If you only need the path:

import os
from django.conf import settings

file_path = os.path.join(settings.STATIC_ROOT, 'file.txt')

with open(file_path, 'r') as source:
    # do stuff
  • Please notice that you need to put your file in a directory like this: my_app/static/my_app/file.txt

for more information you can refer to Django docs .

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