os模块及os.path模块的应用举例

1. 获取当前目录下所有文件类型的统计及文件夹统计

import os


list_all = os.listdir(os.curdir)#os.curdir表示当前目录更准确,listdir返回目录所有文件及文件夹的目录列表

sum_dict = dict() #生产一个空字典


for each in list_all:

if os.path.isdir(each):

sum_dict.setdefault('文件夹',0)

sum_dict['文件夹']  += 1#字典键值取法

else:

ext = os.path.splitext(each)[1]

sum_dict.setdefault(ext,0)

sum_dict[ext] += 1

for eachtype in sum_dict.keys():

print('该目录下共有类型[%s]的文件数量%d个'%(eachtype, sum_dict[eachtype]))


2.在某个目录及子目录中查找某个文件

def search_file(start_dir, target):

os.chdir(start_dir)

list_dir = os.listdir(os.curdir)#获取目录文件列表

for each in list_dir:

if each == target:

print(os.getcwd() + os.seq + each)#找到文件则打印

if  os.path.isdir(each):#如果是文件夹则递归调用

search_file(each, target)

os.chdir(os.pardir)

start_dir = input('请输入要开始查找的目录:')

target = input('请输入要查找的文件名:')

search_file(start_dir, target)

3.在指定的目录及子目录下查找指定后缀名的文件

def search_ext(start_dir, target):

os.chdir(start_dir)

list_dir = os.listdir(os.curdir)#获取目录文件列表

for each in list_dir:

ext = os.path.splitext(each)[1]

if each in target:

find_list.append(os.getcwd() + os.seq + each + os.lineseq)#添加到列表

if  os.path.isdir(each):#如果是文件夹则递归调用

search_file(each, target)

os.chdir(os.pardir)

start_dir = input('请输入要开始查找的目录:')

target = ['.mp4', '.avi', '.rmvb']

find_list = []


search_file(start_dir, target)


f = open(os.getcwd() + os.seq + 'vediolist.txt', 'w')

f.writeline(find_list)

f.close()


4.在当前目录及子目录中的某种类型文件中查找指定的关键字

import os

#=========打印结果=========

def print_pos(key_dict):

keys = key_dict.key()#分离字典的key

keys = sorted(keys)#排序

for each_key in keys:

print('关键字在第 %s 行的第 %s 位置'%(each_key, str(key_dict[each_kkey])))

#========在某行查找关键字==========

def pos_in_line(line, key):

pos = []

begin = line.find(key)

while begin != -1:#在行中找到了

pos.append[begin + 1]

begin = line.find(key, begin + 1)

return pos

#==========在文件中查找==========

def search_in_file(filename, key):

f = open(filename)

count = 0#记录行数

key_dict = dict()


for each_line in f:

count += 1

if key in each_line:

pos = pos_in_line(each_line, key)

key_dict[count] = pos

f.close()

return key_dict

#==========主程序(在目录中查找)==========

def search_key(key, isprt):

all_file = os.walk(os.getcwd())#返回一个三目的元组('路径',[路径包含目录],[路径包含文件])

txt_file = []#定义空列表


for sch in all_file:

for each in sch[2]:

if os.path.splitext(each)[1] == '.txt':

each = os.path.join(i[0], each)#合并路径和文件名

txt_file.append(each)

for each_txt_file in txt_file:

key_dict = search_in_file(each_txt_file, key)

if key_dict:

print('=======================================')

print('在文件%s中找到 %s关键字'%(each_txt_file, ke))

if detail in['YES', 'Yes', '阳台']:

print_pos(key_dict)


key = input('请将给脚本放置到要查找的目录,然后输入要查找关键字:')

detail = input('是否打印关键字%s的位置(YES/NO)'%key)

search_file(key,detail)


import os
#=========打印结果=========
def print_pos(key_dict):
    keys = key_dict.key()#分离字典的key
    keys = sorted(keys)#排序
    for each_key in keys:
        print('关键字在第 %s 行的第 %s 位置'%(each_key, str(key_dict[each_kkey])))

#========在某行查找关键字==========
def pos_in_line(line, key):
    pos = []
    begin = line.find(key)
    while begin != -1:#在行中找到了
        pos.append[begin + 1]
        begin = line.find(key, begin + 1)
    return pos

#==========在文件中查找==========
def search_in_file(filename, key):
    f = open(filename)
    count = 0#记录行数
    key_dict = dict()

    for each_line in f:
        count += 1
        if key in each_line:
            pos = pos_in_line(each_line, key)
            key_dict[count] = pos
    
    f.close()
    return key_dict

#==========主程序(在目录中查找)==========
def search_key(key, isprt):
    all_file = os.walk(os.getcwd())#返回一个三目的元组('路径',[路径包含目录],[路径包含文件])
    txt_file = []#定义空列表

    for sch in all_file:
        for each in sch[2]:
            if os.path.splitext(each)[1] == '.txt':
                each = os.path.join(i[0], each)#合并路径和文件名
                txt_file.append(each)

    for each_txt_file in txt_file:
        key_dict = search_in_file(each_txt_file, key)
        if key_dict:
            print('=======================================')
            print('在文件%s中找到 %s关键字'%(each_txt_file, key))
            if detail in['YES', 'Yes', 'yes']:
                print_pos(key_dict)

key = input('请将给脚本放置到要查找的目录,然后输入要查找关键字:')
detail = input('是否打印关键字%s的位置(YES/NO)'%key)
search_key(key,detail)


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值