321312 发表于 2015-6-19 09:19:52

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 = file_size
      
for each in file_dict.items():    #以列表返回可遍历的(键, 值) 元组数组
    print('%s\t%dBytes' % (each,each))
   
   
   
   
#小甲鱼课后习题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)))

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 = 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:
            if os.path.splitext(each_file) == '.txt':   #根据后缀判断是否为文本文件
                each_file = os.path.join(i,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)


页: [1]
查看完整版本: Python os 模块文件操作