Python文件及目录操作实例详解
本文实例讲述了Python文件及目录操作的方法。分享给大家供大家参考。具体分析如下:
在python中对文件及目录的操作一般涉及多os模块,os.path模块。具体函数以及使用方法在程序中说明。
#!/usr/bin/envpython
#-*-coding=UTF8-*-
importos
importos.pathasop
defchange_dir():
'''
该函数显示及改变前目录
usingchdir()tochangecurrentdir
getcwd()canshowthecurrentworkingdirectory
'''
directory="/tmp"
#使用getcwd()返回当前目录
printos.getcwd()
#chdir改变当前目录为:directory目录
os.chdir(directory)
printos.getcwd()
defshow_filesOfdir(whichDir):
'''
此函数只显示目录下的所有文件
usinglistdir()toshowsallofthefileexecptdirectory
join()functioncatenate'whichDir'withlistdir()returnsvalues
isfile()checkthatfileisaregularfile
'''
#listdir()函数显示前目录的内容
forfileinos.listdir(whichDir):
#利用join()把whichDir目录及listdir()返回值连接起来组成合法路径
file_name=op.join(whichDir,file)
#isfile()函数可以判断该路径上的文件是否为一个普通文件
ifop.isfile(file_name):
printfile_name
defprintaccess(path):
'''
显示文件的最后访问时间,修改时间
shows'path'thelastaccesstime
getatime()returnthetimeoflastaccessofpath
stat()returninformationofafile,useitsst_atimereturnthetimeoflastaccess
ctime()returnastringoflocaltime
'''
importtime
#利用ctime()函数返回最后访问时间
#getatime()函数返回最后访问时间,不过是以秒为单位(从新纪元起计算)
printtime.ctime(op.getatime(path))
#stat()函数返回一个对象包含文件的信息
stat=os.stat(path)
#st_atime最后一次访问的时间
printtime.ctime(stat.st_atime)
printthemodifytime
print"modifytimeis:",
printtime.ctime(op.getctime(path))
print"modifytimeis:",
#st_ctime最后一次修改的时间
printtime.ctime(stat.st_ctime)
defisDIR(path):
'''
一个os.path.isdir()函数的实现
Implementisdir()functionbymyself
'''
importstat
MODE=os.stat(path).st_mode
#返回真假值
returnstat.S_ISDIR(MODE)
if__name__=="__main__":
change_dir()
show_filesOfdir('''/root''')
printaccess('/etc/passwd')
printisDIR('/etc')
希望本文所述对大家的Python程序设计有所帮助。