os.getcwd()与os.path.dirname(__file__)

在学习python的os模块时,遇到了两种获得当前目录的方法:
1.os.getcwd()
2.os.path.dirname(file)
下面探索一下他们的区别:
1.在F:\AI\Allchapter\pythonscientic\chapter05 中创建fileComment.py

import os

def getcwd():
    print('os.getcwd()方法:',os.getcwd())

def pathDirname():
    print('os.path.dirname()方法:',os.path.dirname(__file__))

getcwd()
pathDirname()

结果:
在这里插入图片描述
2.在F:\AI\Allchapter\pythonscientic\data 中创建test.py

from pythonscientic.chapter05 import fileComment

fileComment.getcwd()
fileComment.pathDirname()

结果:
在这里插入图片描述

os.getcwd()就返回的是调用执行它的路径
os.path.dirname(__file__)返回的是绝对路径

++++++++++++++++++++++++++++++++++++++++++++++
修改fileComment.py代码:

import os

def getcwd():
    print('os.getcwd()方法:',os.getcwd())

def pathDirname(file):
    print('os.path.dirname()方法:',os.path.dirname(file))

get.cwd()
pathDirname(__file__)

结果不变
修改test.py代码:

from pythonscientic.chapter05 import fileComment

fileComment.getcwd()
fileComment.pathDirname(__file__)

结果:
在这里插入图片描述
所以os.path.dirname()获得的路径取决于__file__所在的路径。

猜你喜欢

转载自blog.csdn.net/qq_37287621/article/details/83026715