[Django]-Read file in Django Management Command

2đź‘Ť

âś…

When you use an absolute path, it is taken literally i.e. from starting from the root of the filesystem i.e. /.

When you use a relative path i.e. without / at start, it is resolved from the directory where script is invoked from, not where the script actually lies in the filesystem.

So when you invoke the Django management command via e.g. ./manage.py <command>, it looks for a path starting from the current directory of manage.py i.e. os.path.dirname('manage.py'). If you give the path as static/json/spreadsheets.json, the full path it looks for is:

os.path.join(
    os.path.abspath(os.path.dirname('manage.py')),
    '/static/json/spreadsheets.json'
)

So you need to make sure you have the spreadsheets.json file in the right directory. A better approach would be to use an absolute path for these kind of scenarios. If you’re on GNU/Linux, you can use:

readlink -f static/json/spreadsheets.json

to get the absolute path.


Also, rather than hardcoding the file, you should take the file as an argument to the management command. Django management command uses argparse for argument parsing, so you can take a peek at the doc.

👤heemayl

0đź‘Ť

First of all: ~ symbol should not work in this case, because it’s just a glob which is being expanded to full path by *nix shell, so in this case it can’t be expanded as shell is not involved here.
Leading / symbol will move you to the root directory.

I don’t know all situation (because you didn’t provided info about in which directory you run this command and where the file is located in comparison to that directory.

But you can use method getcwd from os library like this:

import os
print(os.getcwd())

Or from debugger, to get know your current location. Then you can pass absolute path to file or use “..” to get to parent directory if needed or even change current working directory using os.chdir() method, but it’s not recommended to do because it can have some side-effects on Django or other libraries used in project which doesn’t expect that directory could be changed in runtime.

Leave a comment