Using os module to write a program that can realize the output of dir-l
Under Linux, the commands ls and dir have the same function: print the current folder directory.
Note: ls is the original command of Linux, dir is the command of the original dos, and Linux chooses to be compatible with this dos command, so dir and ls are functionally the same.
1. Ls command
Common ls commands are:
Ls # shows files and folders that are not hidden
Ls-l # shows the details of files and folders that are not hidden
Ls-a # displays all files in the current directory (including. Hidden file at the beginning)
Note: total is the size of the memory block (block) occupied by all files in the current directory, which is the sum of the values in the first column of the following figure.
2. Python implements dir-l command
For writing a program that can output dir-l using the os module, you must first understand the meaning of each field. Please refer to:
Https://baike.baidu.com/item/ls%20-l/5261110?fr=aladdin
Obviously the difficulty is how to get file permissions, file size, and file creation time.
Import os
Import time
Import stat
Import math
From pwd import getpwuid
From grp import getgrgid
FILE_PERMS = [
{'ringing: stat.S_IRUSR,' wicked: stat.S_IWUSR, 'Xerox: stat.S_IXUSR}
{'ringing: stat.S_IRGRP,' wicked: stat.S_IWGRP, 'Xerox: stat.S_IXGRP}
{'ringing: stat.S_IROTH,' wicked: stat.S_IWOTH, 'Xerox: 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% HRV% 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): http://www.0510bhyy.com/ of Wuxi artificial abortion Hospital
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))