3.2目录操作(files)
Python os模块提供了一个统一的操作系统接口函数,这些接口函数通常是平台指定的,os模块能在不同操作系统平台(如nt或posix)中的特定函数间自动切换,从而能实现跨平台操作。
3.2.1获取当前工作目录
os.getcwd():获取当前工作目录,即当前Python脚本工作的目录路径
>>> import os
>>> os.getcwd()
'D:\\python'
>>>
3.2.2改变当前工作目录
os.chdir():改变当前脚本工作目录,相当于shell下的cd命令
>>> import os
>>> os.getcwd()
'D:\\python'
>>> os.chdir("c:\\users")
>>> os.getcwd()
'c:\\users'
>>>
3.2.3 os.curdir/os.pardir/os.name
os.curdir:os.curdir==”.”
os.pardir: os.pardir==”..”,返回当前目录的父目录,也就是上一级目录”..”
os.name:获取当前使用的操作系统类型(其中”nt”是windows,”posix”是linux或者unix)
>>> import os
>>> os.curdir=="."
True
>>> os.pardir==".."
True
>>>>>> os.getcwd()
'c:\\users'
>>> os.chdir(os.pardir) #相当于os.chdir(“..”)
>>> os.getcwd()
'c:\\'
>>> os.name
'nt'
>>>
3.2.4创建目录
os.mkdir(path[,mode=0777]):生产单级目录;相当于linux中的mkdir dirname.参数mode表示生成目录的权限,默认是超级权限,也就是0777
>>> import os
>>> os.mkdir("d:\\newpath") #在d盘下生成一个名为newpath的目录
>>> os.mkdir("d:\\newpath") #如果目录已经存在,会报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 183] : 'd:\\newpath'
>>>
os.makedirs(path[,mode=0777]):可生成多层递归目录,父目录如果不存在,递归生成。.参数mode表示生成目录的权限,默认是超级权限,也就是0777
>>> import os
>>> os.makedirs("d:\\newpath\\test") #在d盘下生成newpath目录,并在目录下新建test目录
>>> os.makedirs("d:\\newpath\\test") #如果目录已经存在,会报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\os.py", line 157, in makedirs
mkdir(name, mode)
WindowsError: [Error 183] : 'd:\\newpath\\test'
>>>
3.2.5删除目录
os.rmdir(path):删除单级空目录,若目录不为空则无法删除并保错,目录不存在也会报错;相当于linux中的rmdir dirname.
>>> import os
>>> os.rmdir("d:\\newp") #删除d盘下newp目录
>>> os.rmdir("d:\\newp")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 2] : 'd:\\newp'
>>>
os.removedirs(path):若目录为空,则删除,并递归到上一句目录,若也为空,则删除,依次类推。
>>> import os
>>> os.removedirs("d:\\newpath\\test") #成功删除newpath和test目录
>>>
3.2.6列表输出目录
os.listdir(path):列出指定目录下的所有文件和子目录,包括隐藏文件或目录,并以列表形式返回
>>> import os
>>> os.listdir("d:\\python")[0:4] #输出目录下前4个文件或者子目录
['11.py', '1220test.py', '20180110test.py', 'a.txt']
>>>
3.2.7重命名文件/目录
os.rename(oldname,newname):重命名文件/目录
>>> import os
>>> os.rename("d:\\b.txt","d:\\btest.txt") #b.txt文件被命名为btest.txt
>>>
3.2.8获取文件/目录信息
os.stat(filename):以元组的形式返回文件/目录的相关系统信息
>>>import os
>>> os.stat("d:\\python")
nt.stat_result(st_mode=16895, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid
=0, st_size=8192L, st_atime=1516259385L, st_mtime=1516259385L, st_ctime=15014653
79L)
>>>
3.2.9修改文件时间属性
os.utime(path,(atime,mtime)):修改文件的时间属性,设置文件的access and modified time(访问和修改时间)为给定的时间
>>> import os
>>> os.utime("d:\\newfile.txt",(1375448978,1369735977))
>>> os.stat("d:\\newfile.txt")
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid
=0, st_size=48L, st_atime=1375448978L, st_mtime=1369735977L, st_ctime=1516071060
L)
>>>
3.2.10运行shell命令
os.system(command):运行shell命令,可以在python的编译环境下运行shell的command命令
>>> import os
>>> os.system("dir d:\\python*.*")
驱动器 D 中的卷没有标签。
卷的序列号是 A4D1-474C
d:\ 的目录
2018/01/18 15:09 <DIR> python
0 个文件 0 字节
1 个目录 160,629,645,312 可用字节
0
>>>
3.2.11创建临时文件
os.tmpfile():以”w+b”(二进制覆盖式读写)的模式创建并打开一个临时文件
>>> import os
>>> file=os.tmpfile()
>>> file.write("hi\n")
>>> file.write("hello\n")
>>> file.seek(0,0)
>>> for i in file:
... print i
...
hi
hello
>>> print file
<open file '<tmpfile>', mode 'w+b' at 0x0000000002763150>
>>> file.close()
>>>
3.2.12获取当前操作系统相关字符或者数据
os.sep:输出操作系统的特定路径分隔符;win下为”\”,Linux下为”/”
os.pathsep:输出用于分割文件路径的字符串
os.linesep:输出当前平台使用的行终止符,win下为”\r\n”,Linux下为”\n”,Mac使用”\r”.
os.environ:获取系统环境变量,以字典的格式输出
>>> import os
>>> os.sep
'\\'
>>> os.pathsep
';'
>>> os.linesep
'\r\n'
>>> os.environ
{'TMP': 'C:\\Users\\pangwei\\AppData\\Local\\Temp'}
3.2.13文件操作权限
os.access(path,mode):输出文件权限模式;W写,R读,X可执行,输出True or Fasle
>>> import os
>>> os.access("d:\\newfile.txt",os.W_OK) #判断当前是否拥有文件的写权限
True
>>> os.access("d:\\newfile.txt",os.R_OK)
True
>>> os.access("d:\\newfile.txt",os.X_OK)
True
>>>
os.chmod(path,mode):修改文件的权限
>>> import os
>>> os.chmod("d:\\newfile.txt",0777) #修改文件权限为超级权限(0777),可读可写可执行
>>>
3.2.14文件遍历os.walk()
os.walk(top,topdown=True,οnerrοr=None,followlinks=False):此函数返回一个列表,列表中的每一个元素都是一个元组,该元组有三个元素,分别表示每次遍历的路径名(root),目录列表(dirs)和文件列表(files),一般使用格式为:
for root,dirs,files in os.walk(path,topdown=False):
….
参数说明:
top:表示要遍历的目录树的路径
topdown:表示首先返回目录树下的文件,然后遍历目录树下的子目录,默认值为True。值设置为False时,表示先遍历目录树下的子目录,返回子目录下的文件,最后返回根目录下的文件。
onerror:默认值是None,表示忽略文件遍历时产生的错误,如果不为空,则提供一个自定义的函数提示错误信息后继续遍历或者抛出异常终止遍历。
followlinks:默认情况下,os.walk不会遍历软链接指向的子目录,若有需要可以将followlinks设定为True
3.2.15路径操作方法(os.path模块)
os.path.dirname(path):os.path模块中的方法,返回path的目录路径,也就是os.path.split(path)的第一个元素。
os.path.basename(path):返回path最后的文件名,如果path以/或者\结尾,就会返回空值,也就是os.path.split(path)的第二个元素
os.path.exists(path):判断目录或者文件是否存在,如果存在返回True,否则返回False。
>>> import os.path
>>> os.path.exists("d:\\newfile.txt")
True
>>>
os.path.isabs(path):判断path是否是绝对路径,如果是返回True,否则返回False。
>>> import os.path
>>> os.path.isabs("d:\\newfile.txt")
True
>>>
os.path.isfile(path):判断path是否是文件,如果是返回True,否则返回False。
>>> import os.path
>>> os.path.isfile("d:\\newfile.txt")
True
>>>
os.path.isdir(path):判断path是否是目录,如果是返回True,否则返回False。
>>> import os.path
>>> os.path.isdir("d:\\newfile.txt")
False
>>>
os.path.getsize(name):获得文件大小,如果name是目录返回0L,如果name代表的目录或者文件不存在,则会报WindowsError异常
>>>import os.path
>>> os.path.getsize("d:\\newfile.txt")
48L
>>>
os.path.join(a,*p):连接两个或更多的路径名,中间以”\”分隔,如果所给的参数中都是绝对路径名,那只保留最后的路径,先给的将会被弄丢
>>> import os.path
>>> os.path.join("d:\\aa","test","a.txt")
'd:\\aa\\test\\a.txt'
>>> os.path.join("d:\\aa","d:\\test","d:\\a.txt")
'd:\\a.txt'
>>>
os.path.splitext (path):分离文件名和扩展名
>>>import os
>>> os.path.splitext("d:\\stdout.txt")
('d:\\stdout', '.txt')
>>>
os.path.splitdrive (path):拆分驱动器和文件路径,并以元组返回结果,主要对win有效,Linux元组第一个总是空。
>>> os.path.splitdrive("d:\\stdout.txt")
('d:', '\\stdout.txt')
>>>
os.path.getatime (file_name):返回文件最后的存取时间,返回的是时间戳,可以引入time包对时间进行处理
>>> import os
>>> import time
>>> Lasttime=os.path.getatime("d:\\stdout.txt") #获取文件最后存取时间
>>> print Lasttime
1516608557.96
>>> formattime=time.localtime(Lasttime) #将时间戳转成时间元组
>>> print formattime
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=22, tm_hour=16, tm_min=9, tm_se
c=17, tm_wday=0, tm_yday=22, tm_isdst=0)
>>> print time.strftime("%Y-%m-%d %H:%M:%S",formattime) #格式化时间元组为时间字符串
2018-01-22 16:09:17
>>>
os.path.getctime (file_name):返回文件或者目录的创建时间,返回的是时间戳,在Unix系统上是文件最近的更改时间,在Win上是文件或者目录的创建时间
>>> import os
>>> import time
>>> lastTime=os.path.getctime("d:\\stdout.txt") #获取文件的创建时间
>>> print lastTime
1516608557.96
>>> FormatTime=time.localtime(lastTime) #将时间戳转换为时间元组
>>> print FormatTime
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=22, tm_hour=16, tm_min=9, tm_se
c=17, tm_wday=0, tm_yday=22, tm_isdst=0)
>>> print time.strftime("%Y-%m-%d %H:%M:%S",FormatTime) #格式化时间戳
2018-01-22 16:09:17
>>>
os.path.getmtime (file_name):获取文件最后的存取时间
os.path.walk (top,func,arg):遍历目录路径:
top:表示需要遍历的目录树的路径;
func表示回调函数,对遍历路径进行处理的函数。所谓回调函数,是作为某个函数的的参数使用,当某个时间触发时,程序将调用定义好的回调函数处理某个任务。该回调函数必须提供3个参数:第
1个参数为walk()的参数arg,第2个参数表示目录列表dirname
,第3个参数表示文件列表names。
arg:是传递给回调函数func的元组,为回调函数提供处理参数,回调函数的第一个参数就是用来接收这个传入的元组的,参数arg可以为空。
#coding=utf-8
import os
#回调函数
def find_file(arg, dirname, files):
#for i in arg:
#print i
for file in files:
file_path = os.path.join(dirname, file)
if os.path.isfile(file_path):
print "file:%s" %file_path
#调用
os.path.walk(r"d:\python", find_file, (1,2))