Python 中的一些目录命令
主要探究__file__
,getcwd()
直接用代码测试
目录结构
localhost:workdir didi$ tree .
.
└── script_dir
├── __init__.py
├── exec.py
├── index.py
└── models
├── __init__.py
└── model.py
2 directories, 5 files
代码:
models/model.py:
import os
def main():
print('__file__:', __file__)
print(os.path.split(os.path.realpath(__file__))[0])
print('getcwd():', os.getcwd())
if __name__ == '__main__':
main()
index.py
from models.model import main
main()
exec.py
import os
f = open(os.path.split(os.path.realpath(__file__))[0] + '/models/model.py', 'r')
exec(f.read())
执行效果
localhost:workdir didi$ pwd
/Users/didi/workdir
localhost:workdir didi$ python3 script_dir/index.py
__file__: /Users/didi/workdir/script_dir/models/model.py
/Users/didi/workdir/script_dir/models
getcwd(): /Users/didi/workdir
localhost:workdir didi$ python3 script_dir/exec.py
__file__: script_dir/exec.py
/Users/didi/workdir/script_dir
getcwd(): /Users/didi/workdir
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