第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > python_获取文件及文件夹大小修改时间

python_获取文件及文件夹大小修改时间

时间:2019-08-31 13:30:15

相关推荐

python_获取文件及文件夹大小修改时间

获取文件大小

关键函数是

os.path.getsize(file)

获取文件夹大小

没有直接的函数,但是可以通过遍历文件夹,将每个文件的大小叠加

关键函数

for root, dirs, files in os.walk(filePath):for f in files:fsize += os.path.getsize(os.path.join(root, f))

python2和python3稍微有点区别,在python2里面,不能直接将文件路径给os.path.getsize(),因为它不识别中文路径

需要将中文字符转换一下

unicode(filePath,'utf8'

获取文件创建时间,最后修改时间,访问时间

关键函数

os.path.getctime(filePath)#获取创建时间,返回值是标准时间,需要转换os.path.getmtime(filePath)#获取最后修改时间,返回值是标准时间,需要转换os.path.getatime(filePath)#获取访问时间,返回值是标准时间,需要转换

windows上面很奇怪,目前看到的是文件的创建时间和访问时间是一致的,但是文件夹的不一样

有一个博客可以参考一下 /greenerycn/archive//07/11/why_LastAccessTime_diff_to_LastWriteTime.html

最后全部代码如下:

# -*- coding: utf-8 -*-# @Date: -11-12 14:28:14# @Author : Jimy_Fengqi (jmps515@)# @Link: /qiqiyingse# @Version : V1.0# @pyVersion: 3.6import osimport sysimport time,datetime#获取文件的大小,结果保留两位小数def get_FileSize(filePath):def getsize(filePath):if pyversion == '2':return os.path.getsize(unicode(filePath,'utf8'))#主要处理中文命名的文件else:return os.path.getsize(filePath)pyversion=sys.version[0]fsize=0if os.path.isdir(filePath):#通过walk函数迭代for root, dirs, files in os.walk(filePath):for f in files:fsize += getsize(os.path.join(root, f))#如果目录文件中包含有中文命名的文件或者文件夹,那么使用python2将会报错,通过walk函数返回的文件list,并不会转换中文else:fsize =getsize(filePath)print(fsize)fsize = fsize/float(1024)if fsize>1024:fsize = fsize/float(1024)return str(round(fsize,2))+'MB'else:return str(round(fsize,2))+'KB'#把时间戳转化为时间: 1479264792 to -11-16 10:53:12def TimeStampToTime(timestamp):timeStruct = time.localtime(timestamp)return time.strftime('%Y-%m-%d %H:%M:%S',timeStruct)#获取文件的访问时间def get_FileAccessTime(filePath):pyversion=sys.version[0]if pyversion == '2':filePath = unicode(filePath,'utf8')#python2需要使用unicode转换一下t = os.path.getatime(filePath)return TimeStampToTime(t)#'''获取文件的创建时间'''def get_FileCreateTime(filePath):pyversion=sys.version[0]if pyversion == '2':filePath = unicode(filePath,'utf8')#python2需要使用unicode转换一下t = os.path.getctime(filePath)return TimeStampToTime(t)#'''获取文件的修改时间'''def get_FileModifyTime(filePath):pyversion=sys.version[0]if pyversion == '2':filePath = unicode(filePath,'utf8')#python2需要使用unicode转换一下t = os.path.getmtime(filePath)return TimeStampToTime(t)#普通文本文件print('创建时间:'+get_FileCreateTime('test.txt'))print('修改时间:'+get_FileModifyTime('test.txt'))print('访问时间:'+get_FileAccessTime('test.txt'))print('文件大小:'+ str(get_FileSize('test.txt')))#音频文件print('创建时间:'+get_FileCreateTime('过火.mp3'))print('修改时间:'+get_FileModifyTime('过火.mp3'))print('访问时间:'+get_FileAccessTime('过火.mp3'))print('文件大小:'+ str(get_FileSize('过火.mp3') ))#判断文件夹大小print('创建时间:'+get_FileCreateTime('TxtSpliter'))print('修改时间:'+get_FileModifyTime('TxtSpliter'))print('访问时间:'+get_FileAccessTime('TxtSpliter'))print('文件大小:'+ str(get_FileSize('TxtSpliter')))

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。