前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python os 模块文件操作

Python os 模块文件操作

作者头像
py3study
发布2020-01-15 17:44:02
4880
发布2020-01-15 17:44:02
举报
文章被收录于专栏:python3python3python3
#【Python】计算当前文件夹下所有文件的大小
import os
all_files = os.listdir(os.curdir)            #os.curdir表示当前目录。也可使用'.'
file_dict = dict()                           #声明一个空字典
for each_file in all_files:
    if os.path.isfile(each_file):            #判断是否是文件
        file_size = os.path.getsize(each_file)
        file_dict[each_file] = file_size
       
for each in file_dict.items():    #以列表返回可遍历的(键, 值) 元组数组
    print('%s\t%dBytes' % (each[0],each[1]))
    
    
    
    
#小甲鱼课后习题30.4
def print_pos(key_dict):
    keys = key_dict.keys()
    keys = sorted(keys) #由于字典是无序的,我们这里对行数进行排序
    for each_key in keys:
        print('关键字出现在第%s行,第%s个位置。' % (each_key,str(key_dict[each_key])))

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(file_name,key):
    with open(file_name) as f:
        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
    return key_dict

def search_files(key,detail):
    all_files = os.walk(os.getcwd())  #第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。
    txt_files = []

    for i in all_files:               #直接打印all_files神马也不显示
        for each_file in i[2]:
            if os.path.splitext(each_file)[1] == '.txt':   #根据后缀判断是否为文本文件
                each_file = os.path.join(i[0],each_file)
                txt_files.append(each_file)
    for each_txt_file in txt_files:
        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_files(key,detail)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-06-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档