python3获取文件目录和文件
代码语言:javascript复制import os,sys
if __name__=="__main__":
print("__file__ = %s" % __file__)
#获取文件相对路径
print("sys.argv[0]) = %s" % sys.argv[0])
#获取文件的全路径加文件名
print("sys.path[0] = %s " % sys.path[0])
#获取文件的全路径
print("os.getcwd() = %s" % os.getcwd())
#获取当前目录路径(和linux的pwd一样)
print("os.path.realpath(__file__) = %s " % os.path.realpath(__file__))
#获取文件的全路径加文件名
print("os.path.abspath(__file__) = %s " % os.path.abspath(__file__))
#获取文件的绝对路径加文件名
print("os.path.dirname(os.path.realpath(__file__)) = %s " % os.path.dirname(os.path.realpath(__file__)))
#获取文件路径
print("os.path.basename(os.path.realpath(__file__)) = %s " % os.path.basename(os.path.realpath(__file__)))
#获取文件名
print("os.path.split(os.path.realpath(__file__))[0] = %s " % os.path.split(os.path.realpath(__file__))[0])
#获取文件路径
print("os.path.split(os.path.realpath(__file__))[1] = %s " % os.path.split(os.path.realpath(__file__))[1])
#获取文件名
执行结果为:
代码语言:javascript复制C:UsersAdministratorDesktop>python print.py
__file__ = print.py
sys.argv[0]) = print.py
sys.path[0] = C:UsersAdministratorDesktop
os.getcwd() = C:UsersAdministratorDesktop
os.path.realpath(__file__) = C:UsersAdministratorDesktopprint.py
os.path.abspath(__file__) = C:UsersAdministratorDesktopprint.py
os.path.dirname(os.path.realpath(__file__)) = C:UsersAdministratorDesktop
os.path.basename(os.path.realpath(__file__)) = print.py
os.path.split(os.path.realpath(__file__))[0] = C:UsersAdministratorDesktop
代码语言:javascript复制D:>python C:UsersAdministratorDesktopprint.py
__file__ = C:UsersAdministratorDesktopprint.py
sys.argv[0]) = C:UsersAdministratorDesktopprint.py
sys.path[0] = C:UsersAdministratorDesktop
os.getcwd() = D:
os.path.realpath(__file__) = C:UsersAdministratorDesktopprint.py
os.path.abspath(__file__) = C:UsersAdministratorDesktopprint.py
os.path.dirname(os.path.realpath(__file__)) = C:UsersAdministratorDesktop
os.path.basename(os.path.realpath(__file__)) = print.py
os.path.split(os.path.realpath(__file__))[0] = C:UsersAdministratorDesktop