获取文件的信息,例如绝对路径、文件大小修改时间、访问时间、状态变化时间。来源《Python从入门到精通》。
def formatTime(longtime):
return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(longtime))
def formatByte(number):
for (scale,label) in [(1024*1024*1024,"GB"),(1024*1024,"MB"),(1024,"KB")]:
if number >= scale:
return "%.2f %s"%(number*1.0/scale,label)
elif number==1:
return "1 字节"
else:
byte ="%.2f"%(number or 0)
# 去除结尾的.00,并加上“字节”
return (byte[:-3] if byte.endswith(".00") else byte)+" 字节"
if __name__ =='__main__':
fileinfo = os.stat("readme.txt")
print("文件完整路径:",os.path.abspath("readme.txt"))
print("索引号:",fileinfo.st_ino)
print("设备号:",fileinfo.st_dev)
print("文件大小:",formatByte(fileinfo.st_size))
print("最后一次访问:",formatTime(fileinfo.st_atime))
print("最近一次修改:",formatTime(fileinfo.st_mtime))
print("最后一次状态变化:",formatTime(fileinfo.st_ctime))