[ Python

练习1:

  利用os模块编写一个能实现dir -l输出的程序(注意:dir /l是windows下命令)

#!_*_coding:utf-8_*_
# Author: hkey
import os, time
base_dir = input('enter your dir:')   # 手动输入绝对目录
class file_total(object):
    '''获取文件及目录属性'''
    def __init__(self, path):
        self.__path = path
    def file_sum(self):
        '''统计文件及目录总数'''
        for root, dirs, files in os.walk(self.__path, topdown=False):
            f_sum = 0
            d_sum = 0
            for name in files:
                f_sum += 1
            for name in dirs:
                d_sum += 1
        return f_sum, d_sum
    def file_stat(self):
        '''获取具体文件及目录属性'''
        for f in os.listdir(self.__path):
            dir = os.path.join(self.__path, f)
            # print(f)
            os_stat = os.stat(dir)
            # 日期(年/月/日)
            file_date = time.strftime('%Y/%m/%d', time.localtime(os_stat.st_mtime))
            # 时间(时分秒)
            file_time = time.strftime('%H:%M', time.localtime(os_stat.st_mtime))
            # 文件及目录大小
            file_size = os_stat.st_size
            # 文件名
            file_name = f+'	'
            if os.path.isfile(dir):
                file_stat = '<file>'
            elif os.path.isdir(dir):
                file_stat = '<dir>	'
            print(file_date,'	',file_time,'	',file_stat,'	',file_size,'	',file_name)

f = file_total(base_dir)
f_stat = f.file_sum()
print(f.file_stat())
print('	    %s 个文件
	    %s 个目录' % (f_stat[0], f_stat[1]))
View Code

  练习1主要使用到了os模块,os.walk方法很好用。

练习2:

  编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。

#!_*_coding:utf-8_*_
# Author: hkey
import os, re
file_list = list()
# base_dir = input('enter your dir:')
find_str = input('enter your file str:')
for root, dirs, files in os.walk('.', topdown=False):
    for name in files:
        if re.search(find_str, name):
            print(os.path.join(root, name))
View Code

  练习2主要使用到re正则匹配,str类型通过find和index都无法实现判断。

原文地址:https://www.cnblogs.com/hukey/p/7131213.html