Python: get path to file in sister directory?

前端 未结 4 1440
小鲜肉
小鲜肉 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:23
    import os
    directory = os.path.dirname(os.getcwd())
    final = os.path.join(directory, 'data', 'mydata.xls')
    

    or simply

    os.path.abspath('../data/mydata.xls')
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2021-01-03 00:33

    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
    
    0 讨论(0)
  • 2021-01-03 00:36

    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.

    0 讨论(0)
提交回复
热议问题