Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: get path to file in sister directory?

Tags:

python

I have a file structure like this:

data
   mydata.xls
scripts
   myscript.py

From within myscript.py, how can I get the filepath of mydata.xls?

I need to pass it to xlrd:

book = xlrd.open_workbook(filename)

and relative filepaths like '../data/mydata.xls' don't seem to work.

like image 796
AP257 Avatar asked Sep 21 '10 09:09

AP257


2 Answers

You can use os.path.abspath(<relpath>) to get an absolute path from a relative one.

vinko@parrot:~/p/f$ more a.py
import os
print os.path.abspath('../g/a')

vinko@parrot:~/p/f$ python a.py
/home/vinko/p/g/a

The dir structure:

vinko@parrot:~/p$ tree
.
|-- f
|   `-- a.py
`-- g
    `-- a

2 directories, 2 files
like image 93
Vinko Vrsalovic Avatar answered Sep 18 '22 12:09

Vinko Vrsalovic


If you want to made it independent from your current directory try

os.path.join(os.path.dirname(__file__), '../data/mydata.xls')

The special variable __file__ contains a relative path to the script in which it's used. Keep in mind that __file__ is undefined when using the REPL interpreter.

like image 42
Adam Byrtek Avatar answered Sep 20 '22 12:09

Adam Byrtek