|  | 
 
| 
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  复制代码#coding: UTF-8
#知识点总结
#1.os模块即操作系统模块,详细文档http://bbs.fishc.org/thread-45512-1-1.html
#2.
#实操练习
#1.查询文件夹下各种文件类型的个数
#思路-利用os.listdir得到指定文件夹下各文件的名称,
#之后通过循环,查找特定文件扩展名是否在已得到的文件名中,有则加一。最后输出即可。
#优点:代码简单,思路清晰;缺点:需提前指定文件扩展名,未指定的无法监测其个数
import os
file_name = os.listdir('E:\\test')
print(file_name)
txt = 0
png = 0
py = 0
docx = 0
doc = 0
for each_file in file_name:
    if '.txt' in each_file:
        txt += 1
    elif '.png' in each_file:
        png += 1
    elif '.py' in each_file:
        py += 1
    elif '.docx' in each_file:
        docx += 1
    elif '.' not in each_file:
        doc += 1
print('txt 是 %d, png 是 %d, py 是 %d, docx 是 %d, doc 是 %d' % (txt,png,py,docx,doc))
#2.改进版-查询文件夹下各种文件类型的个数
#思路-通过os.listdir得到文件名称,再对文件名称进行遍历,分离出名称和扩展名
#若扩展名在file_type字典中,其value值赋1;否则原value+1;之后进行下一次循环直到遍历结束
#最后根据键值即文件扩展扩展名,遍历字典file_type输出value即可
import  os
def  seek_extension(path):
    file_type = {}         #建立空字典,有key和value两部分
    file_names = os.listdir(path)            #列举指定目录中的文件名,如a.txt,b.py,c.txt
    for  each_file in file_names:
        file_name_extension = os.path.splitext(each_file)  #分离文件名与扩展名,返回(f_name, f_extension)元组
        if  file_name_extension[1] not in file_type:     #file_name_extension[1]此处即f_extension。
                                                         #file_name_extension非元组嵌套元组,每次都是(name,ext...)
            file_type[file_name_extension[1]] = 1    #例如file_name_extension[1]为txt,字典通过键值key(可为字符串)来精确索引
        else:
            file_type[file_name_extension[1]] += 1
    for eachkey in file_type.keys():
        print("该文件夹下共有类型为【%s】的文件 %d 个" % ( eachkey, file_type[eachkey] ) )
path = input("输入要查找的绝对路径: ")
seek_extension(path)
#3.查询指定文件夹下各文件的大小
#思路-通过os.listdir获得指定目录下文件名,遍历文件,其中通过os.path.getsize即可获得文件大小。
#通过字典来存储文件名和其占用内存大小,遍历输出即可
import os
def  file_size_calc(path):
    file = os.listdir(path)     #得到文件名构成列表如['a.txt','b.py']
    file_size = {}              #key为文件名,value为文件大小,如{'asd.txt':141,'b.py':409}
    for  each_file in file:
        file_size[each_file] = os.path.getsize(path + '\\' + each_file)     #其中path为绝对路径,返回文件大小,单位字节
    for  each_key in file_size.keys():
        print('%s 【%d bytes】' % ( each_key, file_size[each_key] ) )
path = input("请输入要查找位置的绝对路径: ")
while not isabs(path)
{
    path = input("请输入要查找位置的绝对路径: ")
}
file_size_calc(path)
#4.将指定目录下指定格式的文件保存的文件中
import os
doc_path = input('请输入待查找的初始目录:')
while not os.path.isdir(doc_path):              #判断指定路径是否存在且是一个目录
    doc_path = input('输入错误,请重新输入待查找的初始目录:')
save_path=input('请输入文件保存目录:')
while not os.path.isdir(save_path):              #判断指定路径是否存在且是一个目录
    save_path = input('输入错误,请重新输入文件保存目录:')
doc_walk = os.walk(doc_path)   #遍历doc_path路径下所有的子目录,返回一个三元组:(路径, [包含目录], [包含文件])
file_path = []   #建立列表,存储文件地址
for each_part in doc_walk:
    for each_file in each_part[2]:
        if '.avi' or '.mp4' or '.rmvb' in each_file.lower():
            file_path.append(os.path.join(each_part[0],each_file) + '\n' * 2)  #将each_part[0],each_file组合成一个路径名
                                                                               #将路径添加到列在file_path中
print(file_path)
f = open(save_path+'\\content2.txt','w',encoding = 'GBK')
f.writelines(file_path)
f.close()
#5.没看懂,以后再说
import os
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  pos_in_file(file, key):
    dict_key = dict()
    count = 0
    target_file = open(file)
    for  each_line in target_file:
        count += 1
        if  key in each_line:
            pos = pos_in_line(each_line, key)
            dict_key[count] = pos
    target_file.close()
    return dict_key
def  print_key(dict_key):
    keys = dict_key.keys()
    keys = sorted(keys)
    for  each_key in keys:
        print("关键字出现在第 %s 行, 第 %s 个位置" % ( each_key, dict_key[each_key] ) )
def  search_key(path, key):
    os.chdir(path)
    for  each_file in os.listdir(os.curdir):
        if  os.path.isdir(each_file):
            search_key(each_file, key)
            os.chdir(os.pardir)
        if  os.path.isfile(each_file):
            if  os.path.splitext(each_file)[1] == '.txt':
                dict_key = pos_in_file(each_file, key)
                if  dict_key != {}:
                    print('==================================================================================')
                    print("在文件【%s】中找到关键字【%s】" %( (os.getcwd() + os.sep + each_file), key ) )
                    print_key(dict_key)
path = input("请输入要查找的路径: ")
key = input("请输入要查找的关键字: ")
search_key(path, key)
 | 
 |