os.path

os.path --常见路径操作

常用方法:

1、os.path.abspath(path) --返回绝对路径

>>> import os
>>> os.path.abspath('.')
'/home/python/test'

2、os.path.basename(path) --返回文件名

>>> os.path.basename('/home/python/test/walk.py')
'walk.py'

3、os.path.commonprefix(list) --返回list(多个路径)中,所有path共有的最长的路径

>>> path_list = ['/home/python/test/1/a/b','/home/python/test/1/a','/home/python/test/walk.py']
>>> os.path.commonprefix(path_list)
'/home/python/test/'

4、os.path.dirname(path) --返回文件路径(或返回上层目录)

>>> os.path.dirname('/home/python/test/walk.py')
'/home/python/test'

>>> os.path.dirname('/home/python/test')
'/home/python'

5、os.path.exists(path) --如果路径 path 存在,返回 True;如果路径 path 不存在,返回 False

>>> os.path.exists('aaaaa')
False
>>> os.path.exists('/home')
True

6、os.path.expanduser(path) --把path中包含的""和"user"转换成用户目录

>>> os.path.expanduser('~')
'/root'

7、os.path.expandvars(path) --根据环境变量的值替换path中包含的"$name"和"${name}"

os.path.expandvars(path)	根据环境变量的值替换path中包含的"$name"和"${name}"

8、**os.path.getmtime(path) ** --返回最近文件修改时间

>>> os.path.getmtime('/root')
1589722909.3381307

9、os.path.getctime(path) --返回文件 path 创建时间

>>> os.path.getctime('/root')
1589722909.3381307

10、os.path.getsize(path) --返回文件大小,如果文件不存在就返回错误

>>> os.path.getsize('walk.py')
287

11、os.path.isabs(path) --判断是否为绝对路径

>>> os.path.isabs('walk.py')
False
>>> os.path.isabs('/home/python/test/walk.py')
True

12、os.path.isfile(path) --判断路径是否为文件

>>> os.path.isfile('walk.py')
True
>>> os.path.isfile('/root')
False

13、os.path.isdir(path) --判断路径是否为目录

>>> os.path.isdir('walk.py')
False
>>> os.path.isdir('/root')
True

14、os.path.islink(path) --判断路径是否为链接(软链接)

>>> os.path.islink('file.txt')
False
>>> os.path.islink('files.txt')
True

15、os.path.ismount(path) --判断路径是否为挂载点

>>> os.path.ismount('/home')
True
>>> os.path.ismount('/home/python')
False

16、os.path.join(path1[, path2[, ...]]) --把目录和文件名合成一个路径

>>> os.path.join('/home','test')
'/home/test'
>>> os.path.join('/home/','test')
'/home/test'

17、os.path.relpath(path[, start]) --从start开始计算相对路径

>>> os.getcwd()
'/home/python/test'
>>> os.path.relpath('/root')
'../../../root'
>>> os.path.relpath('/home','/root')
'../home'

18、os.path.samefile(path1, path2) --判断目录或文件是否相同

>>> os.path.samefile('file.txt','walk.py')
False
>>> os.path.samefile('file.txt','filek.txt')  #filek.txt为硬链接
True
>>> os.path.samefile('file.txt','files.txt')  #files.txt为软链接
True
>>> 

19、os.path.split(path) --把路径分割成 dirname 和 basename,返回一个元组

>>> os.path.split('file.txt')
('', 'file.txt')
>>> os.path.split('/home/python/test/file.txt')
('/home/python/test', 'file.txt')
posted @ 2020-05-20 23:30  静心&得意  阅读(268)  评论(0编辑  收藏  举报