Python os 模塊文件操作

#【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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章