开发者

Python: get path to file in sister directory?

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.


import os
directory = os.path.dirname(os.getcwd())
final = os.path.join(directory, 'data', 'mydata.xls')

or simply

os.path.abspath('../data/mydata.xls')


From you comments, it seems that book = xlrd.open_workbook(filename) doesn't like relative path. You can create a path relative to the current file __file__ and then take the absolute path that will remove the relative portions (..)

import os

filename = os.path.join(os.path.dirname(__file__), '../data/mydata.xls')
book = xlrd.open_workbook(os.path.abspath(filename))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜