[Python]小甲鱼Python视频第030课(文件系统:介绍一个高大上的东西)课后题及参考解答

# -*- coding: utf-8 -*-
"""
Created on Fri Mar  8 15:49:32 2019

@author: Administrator
"""

                                                  
"""

动动手:
0. 编写一个程序,统计当前目录下每个文件类型的文件数,程序实现如图:
1. 编写一个程序,计算当前文件夹下所有文件的大小,程序实现如图
2. 编写一个程序,用户输入文件名以及开始搜索的路径,搜索该文件是否存在。如遇到文件夹,则进入文件夹继续搜索,程序实现如图
3. 编写一个程序,用户输入开始搜索的路径,查找该路径下(包含子文件夹内)所有的视频格式文件(要求查找mp4 rmvb, avi的格式即可),并把创建一个文件(vedioList.txt)存放所有找到的文件的路径,程序实现如图:
4. 编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符),程序实现如图:

"""

import os

#动动手0
def count_file_format_num():
    file_folder = "F:\\drink_c_02010121\\test9";
    result_dict = dict();
    
    result_dict['无后缀名文件'] = 0
    result_dict['文件夹'] = 0
    
    filelist = os.listdir(file_folder);
    for each in filelist:
        each_full_name = file_folder+'\\'+each
        if os.path.isfile(each_full_name):
            if '.' in each:
                file_name = each.split('.');
                if file_name[-1] in result_dict.keys():
                    result_dict[file_name[-1]] += 1;
                else:
                    result_dict[file_name[-1]] = 1;
            else:
                result_dict['无后缀名文件'] +=1;
        else:
            result_dict['文件夹'] +=1;
                
            
        
    print(' [%s] 中共有[%d]类文件' % (file_folder,len(result_dict.keys())))
    for key in result_dict.keys():
        print("该文件夹下共有类型为【%s】的文件【%d】个" % ('.'+key,result_dict[key]))
        
        
        
        
#动动手1
def get_file_size():
    file_folder = "F:\\drink_c_02010121\\test9\\";
    result_dict = dict();           
    filelist = os.listdir(file_folder);

    for each in filelist:
        each_file_full_name = file_folder + os.sep + each;
        result_dict[each] = os.path.getsize(each_file_full_name)
    
    for key in result_dict.keys():
        print('%s 【%dBytes】' % (key,result_dict[key]));


#动动手2:
def find_file_in_dir(folder_path,target_file_name):
    filelist = os.listdir(folder_path)
    for each in filelist:
        #each_full_name = folder_path +'\\'+ each
        each_full_name = folder_path + os.sep + each;
        if each == target_file_name and os.path.isfile(each_full_name):
            print(each_full_name)
        if os.path.isdir(each_full_name):
            find_file_in_dir(each_full_name,target_file_name)
    
#folder_path = input('请输入待查找的初始目录:')
#target_file_name = input('请输入需要查找的目标文件:')
#find_file_in_dir(folder_path,target_file_name)    


#动动手3
#非递归方式,只能到本层和下一层
def get_spec_file_num():
    file_folder = "F:\\drink_c_02010121\\test9"
    result_list = list();
    filelist = os.listdir(file_folder)
    
    valid_suffix = ['rar','h'];
    
    
    for each in filelist:
        if os.path.isdir(file_folder+'\\'+each):
            sub_file_folder = file_folder +'\\' + each;
            sub_file_list = os.listdir(sub_file_folder)
            for sub_each in sub_file_list:
                filename = sub_each.split('.');
                if len(filename) >=2 and filename[-1] in valid_suffix:
                    result_list.append(sub_file_folder+'\\'+sub_each);
        else:
            filename = each.split('.');
            if len(filename) >= 2 and filename[-1] in valid_suffix:
                result_list.append(file_folder+'\\'+each);
            
    f_out = open('file_list.txt','w');
    
    for each in result_list:
        f_out.writelines(each+'\n');
    f_out.close();
    
    
#递归方式,递归遍历子文件夹
result_list = list()
valid_suffix = ['rar','h'];
def get_spec_file_num_res( folder_path ):
    global result_list
    global valid_suffix
    
    filelist = os.listdir(folder_path)
    for each in filelist:
        if os.path.isdir(folder_path+'\\'+each):
            get_spec_file_num_res(folder_path+'\\'+each);
        else:
            filename = each.split('.');
            if len(filename) >= 2 and filename[-1] in valid_suffix:
                result_list.append(folder_path+'\\'+each);
        
            
    
#动动手4:
#0.遍历文件夹获得以.txt结尾的文件
#1.获取.txt文件的内容,获取关键字的存在与否的信息并打印出来

def get_key_word_info_of_txt_file( folder_path,key_word):

    file_list = os.listdir(folder_path);   
    for each in file_list:
        each_full_name = folder_path + '\\' + each 
        if os.path.isdir(each_full_name):
            get_key_word_info_of_txt_file(each_full_name,key_word)
        elif each.endswith('.txt') and os.path.isfile(each_full_name):
            file_obj = open(each_full_name,'r')
            file_valid = 0;
            lines_count = 0;
            for each_line in file_obj:
                lines_count += 1;
                locs = [];
                #lines = [];
                str_count = each_line.count(key_word);
                index = 0;
                while str_count!=0:
                    index = each_line.find(key_word,index)
                    locs.append(index);
                    index = index + 1;
                    str_count -= 1;
                if len(locs)!=0:  
                    file_valid = 1 if file_valid == 0 else 2;
                    if file_valid == 1:
                        print('文件【%s】中出现关键字【%s】:' % (each_full_name,key_word))
                    print('关键字【%s】出现在 %d 行,第%s 个位置' %(key_word,lines_count,locs));
            file_obj.close()



get_key_word_info_of_txt_file( 'C:\\Users\\fengs\Desktop\\SVN_TEST\\Python\\小甲鱼课后题\\测试文件夹','1')    
    
#count_file_format_num()
#get_file_size()
    
#get_spec_file_num_res('F:\\drink_c_02010121\\test9')
#for each in result_list:
#    print(each)

"""
需要注意的问题:
1. 目录分隔符可以用python提供的 os.sep 来代替,以适应不同的操作系统
2. 我的代码都是用的绝对路径,所以不存在切换目录的问题
3. 若要用相对路径,相关的常量:
    os.curdir   -----> 当前目录
    os.sep      -----> 目录分隔符
    os.chdir()  -----> 切换工作目录
    os.pardir   -----> 当前工作目录的上一层目录
    os.getcwd() -----> 当前工作目录的绝对路径

"""

  

posted @ 2019-03-09 23:03  Alimy  阅读(425)  评论(0编辑  收藏  举报