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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With