Python--小甲鱼学习笔记--第30课:文件系统(os、os.path)

(1)模块:可用代码段的打包。

(2)os、os.path模块中关于文件、目录常用的函数使用方法:

Python是跨平台的语言,也就是说同样的源代码在不同的操作系统下不需要修改就可以同样实现。因此,Python的作者就倒腾了OS模块,有了该模块,就不需要关心什么操作系统下使用什么模块,OS模块会帮你选择正确的模块并调用。

Os模块和os.path模块是两个不同的模块。




0.编写一个程序,统计当前目录下每个文件类型的文件数,程序实现如图:


import os

file_list = os.listdir(os.curdir)
dict_file = dict()

for each in file_list:    
    if os.path.isdir(each):
        dict_file.setdefault('文件夹',0)
        dict_file['文件夹']+=1
    else:
        type_file = os.path.splitext(each)[1]
        dict_file.setdefault(type_file, 0)
        dict_file[type_file]+=1
    
for each_key in dict_file.keys():
    print('该文件夹下共有类型为【%s】的文件 %d 个'%(each_key, dict_file[each_key]))

运行结果:



1.编写一个程序,计算当前文件夹下所有文件的大小,程序实现如图:


代码实现:

import os
 
def file_size():  
    file_list = os.listdir(os.curdir)  
    dict_file = dict()  

    for each_file in file_list:  
        if os.path.isfile(each_file):  
            dict_file.setdefault(each_file,os.path.getsize(each_file))  
            print('%s的大小为:【%d Bytes】'%(each_file,dict_file[each_file]))  

file_size()

运行结果:



2.编写一个程序,用户输入文件名以及开始搜索的路径,搜索该文件是否存在。如遇到文件夹,则进入文件夹继续搜索,程序实现如图:


代码实现:

import os
def search_file(search_dir, obj_file):
    os.chdir(search_dir)

    for each_file in os.listdir(search_dir):
        if obj_file == each_file:
            print(os.path.join(search_dir,obj_file))

        elif os.path.isdir(each_file):
            cur_dir = os.path.join(search_dir,each_file) # 当前搜索目录
            search_file(cur_dir, obj_file) # 递归调用
            os.chdir(os.pardir) # 递归调用后返回上一层目录         

search_dir = input("请输入待查找的初始目录:")
obj_file = input("请输入需要查中安的目标文件:")
search_file(search_dir, obj_file)

运行结果:



3.编写一个程序,用户输入开始搜索的路径,查找该路径下(包含子文件夹内)所有的视频格式文件(要求查找mp4,rmvb,avi的格式即可),并把创建一个文件(vedioList.txt)存放所有找到的文件的路径,程序实现如图:


代码实现:

import os
dir_video = []
def find_video(search_dir,dir_video):
    os.chdir(search_dir)
    
    for each_file in os.listdir(search_dir):
        if os.path.splitext(each_file)[1] in ['.mp4','.rmvb', '.avi']:
            dir_video.append(os.path.join(os.getcwd(),each_file) + os.linesep + os.linesep)

        elif os.path.isdir(each_file):
            cur_dir = os.path.join(os.getcwd(), each_file)
            find_video(cur_dir, dir_video)
            os.chdir(os.pardir)
    return dir_video

search_dir = input("请输入待查找的初始目录:") 
dir_video = find_video(os.getcwd(), dir_video)

f = open(os.path.join(search_dir,'vedioList.txt'),'w')
f.writelines(dir_video)
f.close()

4.编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符),程序实现如图:


代码实现:

import os
def print_keywords(dict_keywords):
    keys = dict_keywords.keys()
    keys = sorted(keys)
    for each in keys:
        print('关键字出现在第 %s 行,第 %s 个位置。'\
              % (each, str(dict_keywords[each])))
    
def line_keywords(line, keywords):
    key_index = []
    start = line.find(keywords)
    while start!=-1:
        key_index.append(start+1)
        start = line.find(keywords, start+1)
    return key_index       
    

def file_keywords(filename, keywords):
    f = open(filename,'r')
    line = 0
    dict_keywords = dict()
    for each_line in f:
        line +=1
        if keywords in each_line:
                key_index = line_keywords(each_line, keywords)
                dict_keywords[line]= key_index
    f.close()
    return dict_keywords

    
def file_search(keywords, flag):
    all_files = os.walk(os.getcwd())
    txt_list = []

    for each in all_files:
        for filename in each[2]:
            if os.path.splitext(filename)[1]== '.txt':
                txt_list.append(os.path.join(each[0],filename))

    for each_txt_file in txt_list:
        dict_keywors = file_keywords(each_txt_file, keywords)
        print('====================================================')
        print('在文件【%s】中找到关键字【%s】' % (each_txt_file, keywords))

        if flag in ['YES', 'Yes', 'yes']:
              print_keywords(dict_keywors)
        
keywords = input("请将该脚本放于待查找的文件夹中,请输入关键字:")
flag = input("请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):")
file_search(keywords, flag)


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值