Discuss / Python / 作业1

作业1

Topic source

B O O M!

#1 Created at ... [Delete] [Delete and Lock User]

#!/usr/bin/env python3

# -*- coding:utf-8 -*-

# 利用os模块编写一个能实现dir -l输出的程序

import os, sys

from datetime import datetime

is_win32 = sys.platform == "win32"

if not is_win32:

    import pwd,grp

# opts, args = getopt.getopt(sys.argv[1:], '-l'), ['list']

dir_flag = "/"

if is_win32:

    dir_flag = "\\"

def print_file_info(file, path, level = 1):

    # ctime = os.path.getctime(file)

    mtime = os.path.getmtime(path)

    size = os.path.getsize(path)

    stat_info = os.stat(path)

    uid = stat_info.st_uid

    gid = stat_info.st_gid

    user = ""

    group = ""

    if not is_win32:

        user = pwd.getpwuid(uid)[0]

        group = grp.getgrgid(gid)[0]

    print(">>>" * level, "---------", " ", user, " ", group, " ", size, " ", datetime.fromtimestamp(int(mtime)), " ", file)

def print_dirs(dir, level = 1):

    if level > MAX_LEVEL:

        return

    for file in os.listdir(dir):

        path = "%s%s%s" % (dir, dir_flag, file)

        if os.path.isdir(path):

            print_file_info(file, path, level)

            print_dirs(path, level + 1)

        elif os.path.isfile(path):

            print_file_info(file, path, level)

MAX_LEVEL = 2

def main():

    file = None

    try:

        file = sys.argv[1]

    except IndexError:

        file = os.path.abspath('.')

    if not os.path.isfile(file) and not os.path.isdir(file):

        raise FileNotFoundError(r"The file is not file or dir:{%s}" % file)

    if os.path.isfile(file):

        print_file_info(file, file)

        return

    print_dirs(file)

if __name__ == '__main__':

    main()


  • 1

Reply