Python中的os.path路径模块中的操作方法总结


Posted in Python onJuly 07, 2016

解析路径
路径解析依赖与os中定义的一些变量:

  • os.sep-路径各部分之间的分隔符。
  • os.extsep-文件名与文件扩展名之间的分隔符。
  • os.pardir-路径中表示目录树上一级的部分。
  • os.curdir-路径中当前目录的部分。

split()函数将路径分解为两个单独的部分,并返回包含这些结果的tuple。第二个元素是路径的最后部分,地一个元素是其他部分。

import os.path
for path in [ '/one/two/three',
        '/one/two/three/',
        '/',
        '.',
        '']:
  print '%15s : %s' % (path, os.path.split(path))

输入参数以os.sep结尾时,最后一个元素是空串。

输出:

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

basename()函数返回的值等价与split()值的第二部分。

import os.path
for path in [ '/one/two/three',
        '/one/two/three/',
        '/',
        '.',
        '']:
  print '%15s : %s' % (path, os.path.basename(path))

整个路径会剥除到只剩下最后一个元素。

输出:

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

dirname()函数返回分解路径得到的第一部分。

import os.path
for path in [ '/one/two/three',
        '/one/two/three/',
        '/',
        '.',
        '']:
  print '%15s : %s' % (path, os.path.dirname(path))

将basename()与dirname()结合,得到原来的路径。

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

splitext()作用类似与split(),不过它会根据扩展名分隔符而不是目录分隔符来分解路径。import os.path

for path in [ '/one.txt',
        '/one/two/three.txt',
        '/',
        '.',
        ''
        'two.tar.gz']:

  print '%21s : %s' % (path, os.path.splitext(path))

查找扩展名时,只使用os.extsep的最后一次出现。

/one.txt : ('/one', '.txt')
  /one/two/three.txt : ('/one/two/three', '.txt')
          / : ('/', '')
          . : ('.', '')
      two.tar.gz : ('two.tar', '.gz')

commonprefix()取一个路径列表作为参数,返回一个字符串,表示所有路径中出现的公共前缀。

import os.path
paths = [ '/one/two/three',
      '/one/two/threetxt',
      '/one/two/three/four',]
for path in paths:
  print 'PATH:', path

print
print 'PREFIX:', os.path.commonprefix(paths)

输出:

PATH: /one/two/three
PATH: /one/two/threetxt
PATH: /one/two/three/four

PREFIX: /one/two/three

建立路径
除了分解现有路径外,还需要从其他字符串建立路径,使用join()。

import os.path
for parts in [ ('one', 'two', 'three'),
      ('\one', 'two', 'three'),
      ('/one', '/two', '/three', '/four'),]:

  print parts, ':', os.path.join(*parts)

如果要连接的某个参数以os.sep开头,前面所有参数都会丢弃,参数会返回值的开始部分。

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

规范化路径
使用join()或利用嵌入变量由单独的字符串组合路径时,得到的路径最后可能会有多余的分隔符或者相对路径部分,使用normpath()可以清除这些内容。

import os.path
for path in [ 'one/two/three',
       'one/./two/three',
       'one/../alt/two/three',
       ]:
  print '%20s : %s' % (path, os.path.normpath(path))

可以计算并压缩有os.curdir和os.pardir构成的路径段。

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

要把一个相对路径转换为一个绝对文件名,可以使用abspath()。

import os.path
for path in [ '.',
       '..',
       'one/two/three',
       'one/./two/three',
       'one/../alt/two/three',
       ]:
  print '%20s : %s' % (path, os.path.abspath(path))

结果是从一个文件系统树最顶层开始的完整路径。

. : C:\Users\Administrator\Desktop
         .. : C:\Users\Administrator
    one/two/three : C:\Users\Administrator\Desktop\one\two\three
   one/./two/three : C:\Users\Administrator\Desktop\one\two\three
one/../alt/two/three : C:\Users\Administrator\Desktop\alt\two\three

文件时间

import os
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(__time__))
print 'Size:', os.path.getsize(__file__)

返回访问时间,修改时间,创建时间,文件中的数据量。

测试文件
程序遇到一个路径名,通常需要知道这个路径的一些信息。

import os.path
filename = r'C:\Users\Administrator\Desktop\tmp'
print 'File    :', filename
print 'Is file?   :', os.path.isfile(filename)
print 'Absoulute  :', os.path.isabs(filename)
print 'Is dir?   :', os.path.isdir(filename)
print 'Is link?   :', os.path.islink(filename)
print 'Mountpoint? :', os.path.ismount(filename)
print 'Exists?    :', os.path.exists(filename)
print 'Link Exists? :', os.path.lexists(filename)

所有测试都返回布尔值。

File    : C:\Users\Administrator\Desktop\tmp
Is file?   : False
Absoulute  : True
Is dir?   : True
Is link?   : False
Mountpoint? : False
Exists?    : True
Link Exists? : True

遍历一个目录树

import os
import os.path
import pprint
def visit(arg, dirname, names):
  print dirname, arg
  for name in names:
    subname = os.path.join(dirname, name)
    if os.path.isdir(subname):
      print '%s/' % name 
    else:
      print ' %s' % name
  print
if not os.path.exists('example'):
  os.mkdir('example')
if not os.path.exists('example/one'):
  os.mkdir('example/one')
with open('example/one/file.txt', 'wt') as f:
  f.write('i love you')
with open('example/one/another.txt', 'wt') as f:
  f.write('i love you, two')
os.path.walk('example', visit, '(User data)')

会生成一个递归的目录列表。

example (User data)
one/

example\one (User data)
 another.txt
 file.txt

一些实际的用法合集:

#创建文件:
os.mknod("test.txt")    创建空文件
fp = open("test.txt",w)   直接打开一个文件,如果文件不存在则创建文件
 
#获取扩展名:
>>> os.path.splitext('/Volumes/Leopard/Users/Caroline/Desktop/1.mp4')[1:]
('.mp4',)
>>> os.path.splitext('/Volumes/Leopard/Users/Caroline/Desktop/1.mp4')[1]
'.mp4'
 
#获取文件名:
>>> print os.path.basename(r'/root/hahaha/123.txt')
123.txt
>>> print os.path.dirname(r'/root/hahaha/123.txt')
/root/hahaha
 
#判断目录或文件的存在:
>>> os.path.exists('/root/1.py')
True
>>> os.path.exists('/root/')
True
>>> os.path.exists('/root')
True
>>> os.path.isdir('/root')
True
 
#改变工作目录:
>>> os.chdir('/home')
>>> os.getcwd()
'/home'
 
#字符串分割:
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
 
#获取文件夹大小(Python2.x):
import os 
from os.path import join, getsize 
  
def getdirsize(dir): 
  size = 0L 
  for root, dirs, files in os.walk(dir): 
   size += sum([getsize(join(root, name)) for name in files]) 
  return size 
  
if __name__ == '__main__':
  filesize = getdirsize('/tmp') 
  print 'There are %.3f' % (filesize/1024/1024), 'Mbytes in /tmp' 
 
#获取文件夹大小(Python3.x):
import os 
from os.path import join, getsize 
  
def getdirsize(dir): 
  size = 0 
  for root, dirs, files in os.walk(dir): 
   size += sum([getsize(join(root, name)) for name in files]) 
  return size 
  
if __name__ == '__main__':
  filesize = getdirsize('/tmp') 
  print ('There are ' + str(filesize/1024/1024) + 'Mbytes in /tmp')
Python 相关文章推荐
Python跳出循环语句continue与break的区别
Aug 25 Python
跟老齐学Python之有容乃大的list(3)
Sep 15 Python
Python三元运算实现方法
Jan 12 Python
详解Python如何生成词云的方法
Jun 01 Python
python3 实现一行输入,空格隔开的示例
Nov 14 Python
pyqt5 删除layout中的所有widget方法
Jun 25 Python
python图形绘制奥运五环实例讲解
Sep 14 Python
Python学习笔记之函数的参数和返回值的使用
Nov 20 Python
解决python使用list()时总是报错的问题
May 05 Python
总结python 三种常见的内存泄漏场景
Nov 20 Python
Python OpenCV中的numpy与图像类型转换操作
Dec 11 Python
Python matplotlib 利用随机函数生成变化图形
Apr 26 Python
简介Python的collections模块中defaultdict类型的用法
Jul 07 #Python
Python的collections模块中的OrderedDict有序字典
Jul 07 #Python
Python的collections模块中namedtuple结构使用示例
Jul 07 #Python
详解Python的collections模块中的deque双端队列结构
Jul 07 #Python
简单掌握Python的Collections模块中counter结构的用法
Jul 07 #Python
Python处理json字符串转化为字典的简单实现
Jul 07 #Python
全面了解python字符串和字典
Jul 07 #Python
You might like
关于UEditor编辑器远程图片上传失败的解决办法
2012/08/31 PHP
php跨域cookie共享使用方法
2014/02/20 PHP
大家在抢红包,程序员在研究红包算法
2015/08/31 PHP
实例讲解YII2中多表关联的使用方法
2017/07/21 PHP
用jquery实现输入框获取焦点消失文字
2013/04/27 Javascript
图片上传判断及预览脚本的效果实例
2013/08/07 Javascript
自己写的Javascript计算时间差函数
2013/10/28 Javascript
javascript中的原型链深入理解
2014/02/24 Javascript
JS+CSS实现带关闭按钮DIV弹出窗口的方法
2015/02/27 Javascript
js实现网页多级级联菜单代码
2015/08/20 Javascript
Javascript 5种方法实现过滤删除前后所有空格
2016/06/22 Javascript
jQuery flip插件实现的翻牌效果示例【附demo源码下载】
2016/09/20 Javascript
Vue报错:Uncaught TypeError: Cannot assign to read only property’exports‘ of object’#‘的解决方法
2017/06/17 Javascript
Angular中自定义Debounce Click指令防止重复点击
2017/07/26 Javascript
vue element自定义表单验证请求后端接口验证
2019/12/11 Javascript
vue中echarts引入中国地图的案例
2020/07/28 Javascript
[01:06:30]DOTA2-DPC中国联赛定级赛 Phoenix vs DLG BO3第二场 1月9日
2021/03/11 DOTA
Python使用函数默认值实现函数静态变量的方法
2014/08/18 Python
python 添加用户设置密码并发邮件给root用户
2016/07/25 Python
Python 模板引擎的注入问题分析
2017/01/01 Python
解决python写入带有中文的字符到文件错误的问题
2019/01/31 Python
python实现邮件自动发送
2019/08/10 Python
用Python解数独的方法示例
2019/10/24 Python
Python程序慢的重要原因
2020/09/04 Python
python自动化办公操作PPT的实现
2021/02/05 Python
北京-环亚运商测试题.net程序员初步测试题
2013/05/28 面试题
初中美术教学反思
2014/01/29 职场文书
科级干部考察材料
2014/02/15 职场文书
小组合作学习反思
2014/02/18 职场文书
技校毕业生自荐信
2014/06/03 职场文书
祖国在我心中演讲稿200字
2014/08/28 职场文书
2014年作风建设工作总结
2014/10/29 职场文书
舞蹈社团活动总结
2015/05/07 职场文书
厉行节约工作总结
2015/08/12 职场文书
2016年五一促销广告语
2016/01/28 职场文书
MySQL多表查询机制
2022/03/17 MySQL