Python之os.path路径模块中的操作方法总结
#os.path模块主要集成了针对路径文件夹的操作功能,这里我们就来看一下Python中的os.path路径模块中的操作方法总结,需要的朋友可以参考下
解析路径
路径解析依赖与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
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之os.path路径模块中的操作方法总结的更多相关文章
- Python之os.path.join()
os.path.join()函数用于路径拼接文件路径. os.path.join()函数中可以传入多个路径: 会从第一个以”/”开头的参数开始拼接,之前的参数全部丢弃. 以上一种情况为先.在上一种情况 ...
- python中os.path下模块总结
import os path =os.path.abspath("abc.text") # 返回绝对路径 print("path:",path) # path: ...
- 洗礼灵魂,修炼python(17)--跨平台操作三剑客—os,os.path.sys模块
os 1.作用: 因为客户基本都是使用不同的操作系统,在不同的系统下,要完成一个项目,那必须跨平台操作,而python本来就是一个跨平台的语言,而有了os模块,则不需要在意什么系统.并且os模块是用于 ...
- Python中os和sys模块中常用的方法
os模块 os模块:该模块提供了一些方便使用操作系统相关功能的函数 os.remove() 删除文件 os.rename() 重命名文件 os.walk() 文件目录遍历器 os.chdir() 改变 ...
- node.js中path路径模块的使用
path模块是node.js中处理路径的核心模块.可以很方便的处理关于文件路径的问题. join() 将多个参数值合并成一个路径 const path = require('path'); conso ...
- python:os.path
__file__ " here = os.path.abspath(os.path.dirname(__file__)) 当"print os.path.dirname(__fil ...
- python的os和sys模块
OS模块: 提供对操作系统进行调用的接口 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目 ...
- Python基础-os和sys模块
os模块提供对操作系统进行调用的接口 import os os.getcwd() # 获取当前工作目录 os.chdir(r'd:\fansik') # 修改对当前工作目录 print(os.curd ...
- Python基础-os、sys模块
一,os模块import os ,sysos.system('ipconfig')#执行操作系统命令,获取不到返回结果 os.popen()#也可以执行操作系统命令,可以返回命令执行结果,但需要rea ...
随机推荐
- vue报错/ style-loader: Adds some css to the DOM by adding a <style> tag
1.1.1. vue-cli搭建的项目引入.styl/css文件报错 http://blog.csdn.net/z852064121/article/details/72660327 / styl ...
- Docker 学习应用篇之一: 初识Docker
Docker 自从2013年以来就非常的火热,无论是从github上的代码活跃度,还是Redhat在RHE6.5中集成对Docker的支持,等等.第一次接触Docker,还是老师给我们介绍的. 1.初 ...
- 专访|HPE测试中心总监徐盛:测试新思维-DevOps,持续测试,更敏捷,更快速
2016年7月22日,「HPE&msup软件技术开放日」将在上海浦东新区,张江高科技园区纳贤路799号科荣大厦小楼2楼举办,msup携手HPE揭秘全球测试中心背后的12条技术实践. 徐盛:HP ...
- C# ArcEngine TOCControl上实现右键
第一种方法:使用contextMenuStrip控件 1.新建一个窗体AttributeTable,并定义一个全局变量mLayer,让主窗体里面的axMapControl1的layer传进来,从而获取 ...
- 统计难题---hdu1251字典树模板
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1251 node *head=(node*)malloc(sizeof(node)); for(int ...
- 浅谈CSRF攻击方式(转)
add by zhj: 在看Django开发的应用时,看到了CSRF,然后搜到了这篇文章,讲的不错.其实CSRF 攻击也蛮简单的.当你登陆网站A后,会在本地存有cookie,在cookie没有过期的情 ...
- 聊一聊Linux中的工作队列2
上一篇文章对工作队列原理以及核心数据结构做了简单介绍,本文重点介绍下workqueue的创建以及worker的管理. 一.工作队列的创建(__alloc_workqueue_key) struct w ...
- ViewPager的OnPageChangeListener三个回调解析
一个native crash最后是重写ViewPager解决的,过程中发现这三个回调还有点绕,于是理了一下 ViewPager有两个操作,一个是用手指滑动翻页,一个是直接setCurrentItem( ...
- javaScript高级教程(二)Scope Chain & Closure Example
<!DOCTYPE html> <html> <head> <meta charset=gb2312 /> <title>js</ti ...
- 常用python包(依赖)Ubuntu下
amqp==1.4.9anyjson==0.3.3apturl==0.5.2beautifulsoup4==4.4.1billiard==3.3.0.23blinker==1.3Brlapi==0.6 ...