Python: get path to file in sister directory?

前端 未结 4 1518
小鲜肉
小鲜肉 2021-01-03 00:06

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.

4条回答
  •  时光取名叫无心
    2021-01-03 00:26

    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))
    

提交回复
热议问题