Python之os.path模块的使用

 os.path模块的作用

主要是解析文件路径的拼接,拆分、组合,跨系统文件符号的兼容等功能

 1、跨系统获取路径常用的符号

import os

print(os.sep)     # \ : 获取路径的分割符
print(os.extsep)  # . : 获取文件名与扩展名分割符
print(os.pardir)  # .. :返回上层目录
print(os.curdir)  # . : 当前目录

 2、路径的分割

import os.path

PATHS = [
    '/one/two/three',
    '/one/two/three/',
    '/',
    '.',
    '',
]

for path in PATHS:
    print('{!r:>17} : {}'.format(path, os.path.split(path)))
ospath_split.py

运行效果

 '/one/two/three' : ('/one/two', 'three')
'/one/two/three/' : ('/one/two/three', '')
              '/' : ('/', '')
              '.' : ('', '.')
               '' : ('', '')

 3、os.path.basename()

import os.path

PATHS = [
    '/one/two/three',
    '/one/two/three/',
    '/',
    '.',
    '',
]

for path in PATHS:
    print('{!r:>17} : {!r}'.format(path, os.path.basename(path)))
ospath_basename.py

 运行效果

 '/one/two/three' : 'three'
'/one/two/three/' : ''
              '/' : ''
              '.' : '.'
               '' : ''

总结:
    basename(),其实就是os.path.split()获取元组的第二个元素

 4、os.path.dirname()

import os.path

PATHS = [
    '/one/two/three',
    '/one/two/three/',
    '/',
    '.',
    '',
]

for path in PATHS:
    print('{!r:>17} : {!r}'.format(path, os.path.dirname(path)))
ospath_dirname.py

 运行效果

 '/one/two/three' : '/one/two'
'/one/two/three/' : '/one/two/three'
              '/' : '/'
              '.' : ''
               '' : ''
总结:
    basename(),其实就是os.path.split()获取元组的第一个元素

 5、os.path.splitext()分割文件名,将文件名和扩展名切分

import os.path

FILES = [
    'filename.txt',
    'filename',
    '/path/to/filename.txt',
    '/',
    '',
    'my-archive.tar.gz',
    'no-extension.',
]

for file_name in FILES:
    print('{!r:>17} : {!r}'.format(file_name, os.path.splitext(file_name)))
ospath_splitext.py

运行效果

   'filename.txt' : ('filename', '.txt')
       'filename' : ('filename', '')
'/path/to/filename.txt' : ('/path/to/filename', '.txt')
              '/' : ('/', '')
               '' : ('', '')
'my-archive.tar.gz' : ('my-archive.tar', '.gz')
  'no-extension.' : ('no-extension', '.')

Process finished with exit code 0

6、os.path.commonprefix(),获取一个列表中路径相同部的前缀包含尾部相同的字符串

import os.path

PATHS = ['/one/two/three/four',
         '/one/two/threefold',
         '/one/two/three/',
         ]

for path in PATHS:
    print('PATH:', path)
print('路径公共部分的前缀', os.path.commonprefix(PATHS))
ospath_commonprefix.py

运行效果

PATH: /one/two/three/four
PATH: /one/two/threefold
PATH: /one/two/three/
路径公共部分的前缀 /one/two/three

 7、os.path.commonpath(),获取一个列表中路径相同部的前缀不包含尾部相同的字符串

import os.path

PATHS = ['/one/two/three/four',
         '/one/two/threefold',
         '/one/two/three/',
         ]

for path in PATHS:
    print('PATH:', path)
print('路径公共部分的前缀', os.path.commonpath(PATHS))
ospath_commonpath.py

运行效果

PATH: /one/two/three/four
PATH: /one/two/threefold
PATH: /one/two/three/
路径公共部分的前缀 \one\two

 8、os.path.join(),多个路径的拼接

import os.path

PATHS = [
    ('one', 'two', 'three'),
    ('/', 'one', 'two', 'three'),
    ('/one', '/two', '/three'),
]

for parts in PATHS:
    print('{} : {!r}'.format(parts, os.path.join(*parts)))
ospath_join.py

 运行效果

('one', 'two', 'three') : 'one\\two\\three'
('/', 'one', 'two', 'three') : '/one\\two\\three'
('/one', '/two', '/three') : '/three'

 9、os.path.expanduser(),用于解析特殊符号的路径如 :~

import os.path

for user in ['', 'dhellmann', 'nosuchuser']:
    lookup = '~' + user
    print('{!r:>15} : {!r}'.format(lookup, os.path.expanduser(lookup)))
ospath_expanduser.py

 运行效果

            '~' : 'C:\\Users\\Administrator'
   '~dhellmann' : 'C:\\Users\\dhellmann'
  '~nosuchuser' : 'C:\\Users\\nosuchuser'

 10、os.path.expandvars(),从环境变量中获值设置路径

import os

os.environ['MYVAR'] = 'VALUE'

print(os.path.expandvars('/path/to/$MYVAR'))
ospath_expandvars.py

运行效果

/path/to/VALUE

 11、os.path.normpath(),清除不规范的路径,返回相对路径

import os.path

PATHS = [
    'one//two//three',
    'one/./two/./three',
    'one/../alt/two/three',
]

for path in PATHS:
    print('{!r:>22} : {!r}'.format(path, os.path.normpath(path)))
ospath_normpath.py

 运行效果

     'one//two//three' : 'one\\two\\three'
   'one/./two/./three' : 'one\\two\\three'
'one/../alt/two/three' : 'alt\\two\\three'

 12、os.path.abspath(),解析特殊路径的符号,返回绝对目录

import os

os.chdir('C:\\')

PATHS = [
    '.',
    '..',
    './one/two/three',
    '../one/two/three',
]

for path in PATHS:
    print('{!r:>21} : {!r}'.format(path, os.path.abspath(path)))
ospath_abspath.py

 运行效果

                  '.' : 'C:\\'
                 '..' : 'C:\\'
    './one/two/three' : 'C:\\one\\two\\three'
   '../one/two/three' : 'C:\\one\\two\\three'

 13、获取当前代码文件的属性

import os.path
import time

print('File         :', __file__)
print('Access time  :', time.ctime(os.path.getatime(__file__)))
print('Modified time:', time.ctime(os.path.getmtime(__file__)))
print('Change time  :', time.ctime(os.path.getctime(__file__)))
print('Size         :', os.path.getsize(__file__))
ospath_properties.py

 运行效果

File         : ospath_properties.py
Access time  : Thu Apr 23 17:13:59 2020
Modified time: Thu Apr 23 17:13:59 2020
Change time  : Wed Jan 15 17:38:00 2020
Size         : 311

 14、判断文件是否存在或是否是软连接等

import os.path

FILENAMES = [
    __file__,
    os.path.dirname(__file__),
    './test.py',
]

for file in FILENAMES:
    print('File        : {!r}'.format(file))
    print('Absolute    :', os.path.isabs(file))
    print('Is File?    :', os.path.isfile(file))
    print('Is Dir?     :', os.path.isdir(file))
    print('Is Link?    :', os.path.islink(file))
    print('Mountpoint? :', os.path.ismount(file))
    print('Exists?     :', os.path.exists(file))
    print('Link Exists?:', os.path.lexists(file))
ospath_tests.py

运行效果

File        : 'D:/Program Files/JetBrains/PyCharmData/PythonStudent/tornado_Test/test.py'
Absolute    : True
Is File?    : True
Is Dir?     : False
Is Link?    : False
Mountpoint? : False
Exists?     : True
Link Exists?: True

File        : 'D:/Program Files/JetBrains/PyCharmData/PythonStudent/tornado_Test'
Absolute    : True
Is File?    : False
Is Dir?     : True
Is Link?    : False
Mountpoint? : False
Exists?     : True
Link Exists?: True

File        : './test.py'
Absolute    : False
Is File?    : True
Is Dir?     : False
Is Link?    : False
Mountpoint? : False
Exists?     : True
Link Exists?: True

 运行效果

posted @ 2020-04-23 17:19  小粉优化大师  阅读(558)  评论(0编辑  收藏  举报