Speldosa
Speldosa

Reputation: 1970

Specify path to sibling folder in a non-absolute way

Let's say that I have a folder, x, containing the two folders foo and bar. Inside foo I have a Python script and inside bar, I have my data (let's say a couple of .txt files). Now, from within my script, I would like to access my data. I could simply use this command and call it a day:

fileList = glob.glob('/absolute/path/to/bar/*.txt')

However, using this method, my script would break if I moved my x folder.

What's the easiest way to specify the path in a relative manner that allows me to move around the parent folder, x, freely?

Upvotes: 3

Views: 5064

Answers (2)

felipsmartins
felipsmartins

Reputation: 13549

I think __file__ is a nice approach:

import glob
import os

# "x" folder
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   
files = glob.glob(os.path.join(base_dir, 'bar', '*.txt'))

Working from top directory is a lot easier. Django and other frameworks does it too.
Also, it solves issues when invoking script from command line and from different locations.

Another approch is usging os.chdir(), changing working directory:

import glob
import os

# same that: cd /absolute path/for/x folder
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

files = glob.glob(os.path.join('bar', '*.txt'))

Zend Framework (PHP) uses the above approach in bootstrap file.

Both solutions works very well for all cases.

Upvotes: 2

Marco Tompitak
Marco Tompitak

Reputation: 658

../ specifies your parent directory, so ../bar/*.txt.

Like John Gordon said, this works assuming you're inside x/foo/ and running the script from there.

If you're not executing the script from its own directory, you'll need to find out where your script currently is. This is not trivial. felipsmartins' solution of using os.path.dirname(os.path.dirname(__file__)) is generally fine, but doesn't work in all cases. See e.g. here: How to properly determine current script directory in Python?

Upvotes: 8

Related Questions