15

简单介绍 os.path 模块常用方法

 2 years ago
source link: https://foofish.net/python-os-path.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

os.path 在python中也算是一个常用的模块,特别是和文件系统打交道时,涉及到文件、目录的操作经常会用到,你去看一些框架的源代码的时候也经常会使用到这些方法。

如果去看官方文档,os.path 大概提供了近20个方法,其实比较常用的方法我总结的9个,你可以跟着操作下,很容易就记住了。其实看方法名都知道具体是做什么的。

os.path.png

1、os.path.abspath

获取文件的绝对路径

path = "test.py"
print(os.path.abspath(path)) # C:\Users\lzjun\workspace\python_scripts\test.py

2、 os.path.basename

获取文件名,不包含目录部分, 如果该路径本身就是个目录,那么返回的就是空

path = "C:/Users/lzjun/workspace/python_scripts/test_path.py"
print(os.path.basename(path))  # test_path.py

path = "../test/"
print(os.path.basename(path)) # 空字符串

3、 os.path.dirname

获取文件的目录部分, dirname + basename 就可以构成文件的完整路径名

path = "C:/Users/lzjun/workspace/python_scripts/test_path.py"
print(os.path.dirname(path))  # C:/Users/lzjun/workspace/python_scripts

4、 os.path.exists

判断路径是否存在,这里的路径包括目录和文件(在linux系统,一切皆文件), 如果你直接复制我的代码,可能返回的结果是False,因为你的系统可能没有这些目录。

path = "C:/Users/lzjun/workspace/python_scripts/test_path.py"
print(os.path.exists(path)) # True

path = "C:/Users/lzjun/workspace/python_scripts"
print(os.path.exists(path)) True

5、 os.path.getsize

获取文件大小,也可以获取目录(所有文件的)大小,取决你你传的路径参数是文件还是目录。单位是字节

path = "C:/Users/lzjun/workspace/python_scripts/test_path.py"
print(os.path.getsize(path)) # 177 

6、 os.path.split

split 方法会将路径切割成两部分,以最后一个斜杠作为切割点,第一部分是文件所在的目录, 第二部分文件名本身。如果传入的path是以“/”结尾,那么第二部就是空字符串

path = "C:/Users/lzjun/workspace/python_scripts/test_path.py"
print(os.path.split(path))  # ('C:/Users/lzjun/workspace/python_scripts', 'test_path.py')

path = "C:/Users/lzjun/workspace/python_scripts/"
print(os.path.split(path))  # ('C:/Users/lzjun/workspace/python_scripts', '')

7、 os.path.join

join是与split对应的方法,用于拼接文件路径,一般用于已知a文件的完整路径,我想在与a同目录下创建个b文件就可以用到join方法。

a_path = "C:/Users/lzjun/workspace/python_scripts/a.py"
dir = os.path.split(a_path)[0]
print(os.path.join(dir, "b.py")) # C:/Users/lzjun/workspace/python_scripts\b.py

8、os.path.isdir

判断路径是否为目录,注意,如果该目录不存在也不会报错,而是直接返回False

path = "C:/Users/lzjun/workspace/python_scripts/"
print(os.path.isdir(path)) # True

9. os.path.isfile

判断路径是否为文件,注意,如果该文件不存在也不会报错,而是直接返回False

print(os.path.isfile(__file__))  # True
a_path = "C:/Users/lzjun/workspace/python_scripts/a.py"
print(os.path.isfile(a_path)) # False (文件压根不存在)

官方文档:https://docs.python.org/3/library/os.path.html

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK