python3---os模板,关于文件路径的处理

2019-06-10  本文已影响0人  小蜗牛的成长

在日常编码中,经常与文件路径打交道,对于文件路径的操作中,总是会遇到一些坑,通常是由于没有彻底理解帮助文档的说明

知识点

在使用os模块中关于文件路径等的处理前,先掌握以下一些os变量:

os模块的通用方法,包括获取文件路径、查看、删除等
os.path常用方法

文件属性:

容易使用错误的方法

os.path.join(),注意构建新的路径时,如果参数以os.sep开头,则之前的所有参数都会丢弃

例如:

import os.path

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

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

结果为【这里是用windows运行,连接符为“\”】:

('one', 'two', 'three') : 'one\\two\\three'
('/', 'one', 'two', 'three') : '/one\\two\\three'
('/', 'one', '/', 'two', 'three') : '/two\\three'
('/one', '/two', '/three') : '/three'
('/one/', '/two', 'three') : '/two\\three'
os.path.dirname()、os.path.basename() 、os.path.split() 方法有相似之处,均是以最后一个os.sep分隔符切分成2部分,只是返回不同的部分而已

例如:

import os.path
PATHS = [
    '/one/two/three',
    '/one/two/three/',
    '/',
    '.',
    '',
]

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

结果:

'/one/two/three' : ('/one/two', 'three')
/one/two/three/' : ('/one/two/three', '')
             '/' : ('/', '')
             '.' : ('', '.')
              '' : ('', '')
os.getcwd()与os.path.expanduser('~')

例如:

 #expanduser()把波浪符(~)转换为用户主目录的名称   
for user in ['', 'dhellmann', 'nosuchuser']:
    lookup = '~' + user
    print('{!r:>15} : {!r}'.format(
        lookup, os.path.expanduser(lookup)
    ))

结果:
注意:如找不到用户的主目录,则返回字符串不变

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

帮助文档:https://pymotw.com/3/os.path/index.html

上一篇 下一篇

猜你喜欢

热点阅读