Python: get path to file in sister directory?

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

提交回复
热议问题