python学习--标准库之os 实例(3)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #列出当前目录下文件的大小和创建日期及文件名,相当于ls -l命令 from datetime import datetime import os pwd = os.path.abspath('.') print(' Size Last Modified Name') print('------------------------------------------------------------') for f in os.listdir(pwd): f_size = os.path.getsize(f) if f_size > 1024: k_size = round(f_size / 1024, 1) f_size = str(k_size) + 'K' if k_size > 1024: m_size = round(k_size / 1024, 1) f_size = str(m_size) + 'M' if m_size > 1024: g_size = round(m_size / 1024, 1) f_size = str(g_size) + 'G' else: f_size = str(f_size) + 'B' mtime = datetime.fromtimestamp(os.path.getmtime(f)).strftime('%Y-%m-%d %H:%M') flag = '/' if os.path.isdir(f) else '' '''if os.path.isdir(f): t = '/' else: t = "" ''' #print('%10d %s %s%s' % (fsize, mtime, f, flag)) print("{:>10}{:^20}{}{}".format(f_size, mtime, f, flag))