Python: get path to file in sister directory?

前端 未结 4 1566
小鲜肉
小鲜肉 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:33

    You can use os.path.abspath() 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
    

提交回复
热议问题