在Linux下命令ls和dir都有相同的功能:打印当前文件夹目录。
注:ls 是Linux的原装命令,dir 是原来dos的命令,Linux选择兼容了此个dos命令,所以dir和ls在功能上是一样的。
1. ls命令
常见的ls命令有:
ls # 显示不隐藏的文件与文件夹
ls -l # 显示不隐藏的文件与文件夹的详细信息
ls -a # 显示当前目录下的所有文件(包含.开头的隐藏文件)
注意:total为当前目录下所有文件占用的内存块(block)的大小,即下图第一列数值之和。
2. Python实现dir -l 命令
对于利用os模块编写一个能实现dir -l输出的程序,首先得了解一下各个字段的含义,请参考:
https://baike.baidu.com/item/ls%20-l/5261110?fr=aladdin
显然难点在于怎样获取文件权限、文件大小、文件创建时间。
import os
import time
import stat
import math
from pwd import getpwuid
from grp import getgrgid
FILE_PERMS = [
{'r': stat.S_IRUSR, 'w': stat.S_IWUSR, 'x': stat.S_IXUSR},
{'r': stat.S_IRGRP, 'w': stat.S_IWGRP, 'x': stat.S_IXGRP},
{'r': stat.S_IROTH, 'w': stat.S_IWOTH, 'x': stat.S_IXOTH}
]
class Info:
def __init__(self, name, size_width=0):
self.width = size_width
statinfo = os.stat(name)
mode = statinfo.st_mode
self.name = name
fmt = "%b %d %H:%M"
self.date = time.strftime(fmt, time.localtime(statinfo.st_mtime))
self.size = statinfo.st_size
allocated_size = statinfo.st_blocks * statinfo.st_blksize
f_bsize = os.statvfs(name).f_bsize
f_block_num = math.ceil(allocated_size / f_bsize)
self.fsize = f_block_num * f_bsize // 1024
self.user = getpwuid(statinfo.st_uid).pw_name
self.group = getgrgid(statinfo.st_gid).gr_name
self.nlink = statinfo.st_nlink
self.perm = 'd' if stat.S_ISDIR(mode) else '-'
for perm in FILE_PERMS:
self.perm += 'r' if mode & perm['r'] else '-'
self.perm += 'w' if mode & perm['w'] else '-'
self.perm += 'x' if mode & perm['x'] else '-'
# magic method: Overrides method in object
def __str__(self):
return "{} {} {} {} {:{width}} {} {}".format(
self.perm, self.nlink, self.user, self.group,
self.size, self.date, self.name, width=self.width)
if __name__ == '__main__':
total = 0
dir_list = []
width = 0
for x in os.listdir('.'):
if x[0] == '.':
continue
item = Info(x)
width = max(width, len(str(item.size)))
total += item.fsize
dir_list.append(x)
print('total', total)
for x in sorted(dir_list, key=lambda z: z.upper()):
print(Info(x, width))