Python 中的一些目录命令

/

2019-4-18

主要探究__file__,getcwd()
直接用代码测试
目录结构

  1. localhost:workdir didi$ tree .
  2. .
  3. └── script_dir
  4. ├── __init__.py
  5. ├── exec.py
  6. ├── index.py
  7. └── models
  8. ├── __init__.py
  9. └── model.py
  10. 2 directories, 5 files

代码:

models/model.py:

  1. import os
  2. def main():
  3. print('__file__:', __file__)
  4. print(os.path.split(os.path.realpath(__file__))[0])
  5. print('getcwd():', os.getcwd())
  6. if __name__ == '__main__':
  7. main()

index.py

  1. from models.model import main
  2. main()

exec.py

  1. import os
  2. f = open(os.path.split(os.path.realpath(__file__))[0] + '/models/model.py', 'r')
  3. exec(f.read())

执行效果

  1. localhost:workdir didi$ pwd
  2. /Users/didi/workdir
  3. localhost:workdir didi$ python3 script_dir/index.py
  4. __file__: /Users/didi/workdir/script_dir/models/model.py
  5. /Users/didi/workdir/script_dir/models
  6. getcwd(): /Users/didi/workdir
  7. localhost:workdir didi$ python3 script_dir/exec.py
  8. __file__: script_dir/exec.py
  9. /Users/didi/workdir/script_dir
  10. getcwd(): /Users/didi/workdir
  11. localhost:workdir didi$

在进行文件操作时,如果是想从用户角度来操作文件,往往是相对于workdir(用户的工作目录)的,但如果是自己的代码想操作一些配置文件,就要用file

Reproduced please indicate the author and the source, and error a link to this page.
text link: //sealbaby.cn/python-path