python os详解

1.os.getcwd()--起始执行目录
获取当前执行程序文件所在的目录,需要注意的是,getcwd不是获取代码所在文件的目录,也不是获取执行文件所在的目录,而是起始执行目录。
目录结构:

test.py
test
    sub_file.py

test.py

from test import sub_file

sub_file.xx()

sub_file.py

import os


def xx():
    print(os.getcwd())

运行:

E:gitcode>python Lottery/test.py
E:gitcode

可见,执行输出的是起始执行目录

2.sys.path[0]或sys.argv[0] --执行文件所在目录
sub_file.py

import sys


def xx():
    print(sys.path[0])

运行:

E:gitcode>python Lottery/test.py
E:gitcodeLottery

3.os.path.dirname(os.path.realpath(file)) --当前文件所在目录
sub_file.py

import os


def xx():
    print(os.path.dirname(os.path.realpath(__file__)))

运行:

E:gitcode>python Lottery/test.py
E:gitcodeLottery	est
原文地址:https://www.cnblogs.com/shijingjing07/p/9468664.html