码迷,mamicode.com
首页 > 其他好文 > 详细

os模块(二)

时间:2018-06-20 18:50:04      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:err   关闭   优先   sdi   basename   python2   分割   分离   cal   

os.path.exists(path)
判断目录/文件是否存在

>> os.path.exists("e:\python")
True
>> os.path.exists("e:\python\1.txt")
True
...
os.path.isfile(file)
判断是否是文件
>> if os.path.isfile("e:\python\1.txt"):
... print "a file"
...
a file
os.path.isdir(file)
判断是否是目录
>> if os.path.isdir("e:\python\1.txt"):
... print "a dir"
...

小练习:
删除一个目录下文件
import os
import os.path
os.chdir("e:\python2")
list1 = os.listdir("e:\python2")
for content in list1:
if os.path.isfile(content):
os.remove(content)

os.stat(path)

用于在给定的路径上执行一个系统 stat 的调用
Path指定路径
返回值:
stat 结构:
?st_mode:?inode 保护模式
?st_ino:?inode 节点号。
?st_dev:?inode 驻留的设备。
?st_nlink:?inode 的链接数。
?st_uid:?所有者的用户ID。
?st_gid:?所有者的组ID。
?st_size:?普通文件以字节为单位的大小;包含等待某些特殊文件的数据。
?st_atime:?上次访问的时间。
?st_mtime:?最后一次修改的时间。
?st_ctime:?由操作系统报告的"ctime"。在某些系统上(如Unix)是最新的元数据更改的时间,在其它系统上(如Windows)是创建时间(详细信息参见平台的文档)。

os.wakl()
概述
os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。
os.walk() 方法是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。在Unix,Windows中有效。
walk()方法语法格式如下:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
参数
top?-- 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)。

root 所指的是当前正在遍历的这个文件夹的本身的地址
dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
topdown?--可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果topdown 参数为 False,walk 会遍历top文件夹,与top 文件夹中每一个子目录。
onerror?-- 可选, 需要一个 callable 对象,当 walk 需要异常时,会调用。
followlinks?-- 可选, 如果为 True,则会遍历目录下的快捷方式(linux 下是 symbolic link)实际所指的目录(默认关闭)。

返回值
该方法没有返回值。

实例:
#coding=utf-8
import os
for root,dirs,files in os.walk("e:\python",topdown=False) :
print "当前目录:",root
for name in files :
print ‘文件名:‘,os.path.join(root,name)
for name in dirs :
print ‘目录名:‘,name

小练习:
打印文件a.txt的文件路径
import os
result_list = []
def find_file(path):
for root,dirs,files in os.walk(path,topdown=False) :
for file in files:
if "a.txt" in file:
result_list.append(os.path.join(root,file))
return result_list

print find_file("e:\python")

2、求一个文件路径下所有文件的数量
import os
def find_file(path):
count_file = 0
for root,dirs,files in os.walk(path,topdown=False) :
for file in files:
print u"文件名",file
count_file += 1
return count_file
print find_file("e:\python")

3、找出txt文件的个数
import os
def find_file(path):
count_file = 0
for root,dirs,files in os.walk(path,topdown=False) :
for file in files:
if "txt" in file:#if file.find("txt") != -1:
count_file += 1
return count_file

print find_file("e:\python")

>> os.path.dirname("e:\python\1.txt")
‘e:\python‘
4、查看目录下的所有文件
方式1:
for root,dirs,files in os.walk("e:\python",topdown=False):
for file in files:
os.chdir(root)
print os.path.abspath(file)
方式2:
for root,dirs,files in os.walk("e:\python",topdown=False) :
for file in files:
print os.path.join(root,file)

os.path.abspath(path)
返回一个文件的绝对路径

>> os.path.abspath("1.txt")
‘E:\python\1.txt‘

os.path.split(file)
将path分割成目录和文件名(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在),并存于元组中返回。

>> os.path.split("e:\python\1.txt")
(‘e:\python‘, ‘1.txt‘) 元组

os.path.dirname(filepath)
返回path的目录路径,其实就是os.path.split(path)的第一个元素

>> os.path.dirname("e:\python\hu.txt")
‘e:\python‘

os.path.basename(filepath)
返回path最后的文件名。如果path以/或\结尾,就会返回空值。即
os.path.split(path)的第二个元素。

>> os.path.basename("e:\python\hu.txt")
‘hu.txt‘

os.path.isabs(path)
判断路径是否是绝对路径

>> os.path.isabs("e:\python\1.txt")
True

os.path.normpath(path)
将path转换成规范的文件路径

>> os.path.normpath("e:/python")
‘e:\python‘
>> os.path.normpath("c:/d/2")
‘c:\d\2‘
>> os.path.normpath("c:/d\2")
‘c:\d\x02‘

os.path.getsize(filepath)
返回文件大小,目录返回4096

>> os.path.getsize("e:\python\1.txt")
39L
>> os.path.getsize("e:\python")
4096L 这个是目录

os.path.join(a, *p)
连接两个或更多的路径名,中间以“\”分隔,如果所给的参数中都是绝对路径名,那先给的绝对路径将会被丢弃。

>> import os
>> os.path.join("e:\python","1.txt")
‘e:\python\1.txt‘

>> os.path.join("e","python","1.txt")
‘e\python\1.txt‘

os.path.splitext(filepaht)
分离文件名与扩展名,切出文件后缀名

>> os.path.splitext("e:\python\1.txt")
(‘e:\python\1‘, ‘.txt‘)

>> file_name = os.path.split("e:\python\1.txt")[1]
>> file_postfix = os.path.splitext(file_name)
>> print file_postfix[1]
.txt

>> os.path.splitext(os.path.split("e:\python\1.txt")[1])[1]
‘.txt‘

小练习:
找出一个目录及子目录下的所有文件名字,不含后缀
filename_list = []
for root,dirs,files in os.walk("e:\python\",topdown = False):
for file in files:
print file
filename_list.append(os.path.splitext(file)[0])
print filename_list

os.path.splitdrive(filepath)
拆分驱动器和文件路径,并以元组返回结果;主要针对win有效,Linux元组第一个总是空

>> import os
>> os.path.splitdrive("e:\python\1.txt") 切盘符
(‘e:‘, ‘\python\1.txt‘)

os.path.getatime(filename)
获取文件的最后访问时间,返回的是时间戳,1970到现在的秒数

>> os.path.getatime("e:\python\hu.txt")
1234567.0

>> time_arr = time.localtime(os.path.getatime("e:\python\1.txt"))
>> time_arr
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=24, tm_hour=16, tm_min=24, tm_sec=40, tm_wday=3, tm_yday=144, tm_isdst=0)
>> time.strftime("%Y-%m-%d %H:%M:%S",time_arr)
‘2018-05-24 16:24:40‘

封装获取文件访问时间函数
import os
import time
def get_file_access_time(file_path):
file_time=os.path.getatime(file_path)
return get_time(file_time)

def get_time(timestamp):
time_arr = time.localtime(timestamp)#返回时间元组
return time.strftime("%Y-%m-%d %H:%M:%S",time_arr)

if name == "main":
print get_file_access_time("e:\python\1.txt"

os.path.getctime(path)
以时间戳的形式返回文件或目录的创建时间,在Unix系统上
是文件最近更改的时间,在Windows上是文件或目录的创建>>> os.path.getctime("e:\python\1.txt")创建时间
1527150280.032749

>> os.path.getctime("e:\python")
1527149411.9510975

os.path.getmtime(path)
以时间戳的形式返回文件或目录的修改时间,

>> os.path.getmtime("e:\python\1.txt")
1527152386.11821
>> os.path.getmtime("e:\python")
1527670010.1196618

os模块(二)

标签:err   关闭   优先   sdi   basename   python2   分割   分离   cal   

原文地址:http://blog.51cto.com/13496943/2131004

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!