How to run a Python script connected to the DB file from another directory?

Question:

Downloads
├── pythonScript
    ├── RANK.db
    └── dbCompare.py

I am trying to run a python script which shows all data from a DB table named RANK.
Above is my directory structure and Downloads directory is where I want to run the python script.

The python script is located at /Downloads/pythonScript/dbCompare.py and I am trying to run it from /Downloads.

In my zsh, I have tried to run it using python pythonScript/dbCompare.py command from /Downloads. But it is telling me that there is no RANK table.

After doing that, I tried to change my working directory to /Downloads/pythonScript then run it again, using python dbCompare.py command in zsh.
Then the python script was working.

The reason why I am trying to run this command from /Downloads is I need to run this command from NodeJS server which is located at /Downloads.

I have checked my db file if there is a typo or something else but I don’t see any.

How do I run this python script from /Downloads?
It is only working in /Downloads/pythonScript/ directory.

Asked By: Onam Kwon

||

Answers:

change the path in
sqlite3.connect(‘rank.db’) to sqlite3.connect(‘relative pathrank.db’)
that’s because of at the first connection python will search in the same dir of the script

Answered By: Abdo Bakry

Check if the db exists before connect() which will create it if it doesn’t.

db = '/path/to/rank.db'
if not os.path.exists(db):
    raise RuntimeError(f'{db} does not exist')
sqlite3.connect(db)
Answered By: Diego Torres Milano
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.