python代码:
#!/usr/bin/python
#-*- coding:utf-8 -*-
import os
import sys
import datetime
import re
def isAscii(ch) :
return ch <= u'\u007f'
def formatByWidth(text, width, align_left=True) :
pad = " " * (width - strlen(text))
if align_left :
return text + pad
else :
return pad + text
def strlen(str) :
count = len(str)
for u in str:
if not isAscii(u) :
count += 1
return count
#return directory total size, unit K
def getDirSize(dir) :
size = 0;
try:
if os.path.isdir(dir) :
for file in os.listdir(dir) :
path = os.path.join(dir, file)
if os.path.isdir(path) :
size += getDirSize(path)
elif os.path.isfile(path) :
size += os.path.getsize(path)
else :
print(file)
except IOError :
pass
finally:
return size;
def getTime(file) :
timestamp = os.path.getmtime(file)
return datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
def formatNum(num):
num=str(num)
pattern=r'(\d+)(\d{3})'
while True:
num,count=re.subn(pattern,r'\1,\2',num)
if count==0:
break
return num
def ls(dir) :
dir = dir.decode('utf-8')
maxLength = 0
for file in os.listdir(dir) :
filenameLen = strlen(file)
if filenameLen > maxLength :
maxLength = filenameLen;
totalSize = 0
filenameWidth = maxLength
timeWidth = 19
sizeWidth = 15
print("%s %s %s" % (formatByWidth("文件名".decode('utf-8'), filenameWidth, False), \
formatByWidth("最后修改日期".decode('utf-8'), timeWidth), \
formatByWidth("大小(字节)".decode('utf-8'), sizeWidth, False)))
for file in os.listdir(dir) :
path = os.path.join(dir, file)
if os.path.isdir(path) :
size = getDirSize(path)
else :
size = os.path.getsize(path)
totalSize += size
print("%s %s %s" % (formatByWidth(file, filenameWidth, False), \
formatByWidth(getTime(path), timeWidth), \
formatByWidth(formatNum(size), sizeWidth, False)))
print("目录总大小:%s(字节)".decode('utf-8') % formatNum(totalSize))
if len(sys.argv) > 1 :
ls(sys.argv[1])
else :
ls('.\\')
通过pyinstaller生成的 ls.exe 文件
将下载的 ls.exe 文件放入C:\Windows\System32目录下,或者通过环境变量设置,按 WIN+R 打开命令窗口,就可像dir一样使用ls命令显示指定目录下所有文件的大小,如“ls”显示当前目录下所有文件的名称,最后修改时间,大小;“ls test”显示当前目录test文件夹下所有文件的大小。