python复习30~31文件系统和pickle

学习内容:文件系统

函数名使用方法
os.getcwd ()返回当前工作目录
os.chdir()改变工作目录
os.listdir(path=’.’)列举指定目录中的文件名
os.mkdir()创建单层目录,若目录已存在则抛出异常
os.makedirs()递归创建多层目录
os.remove()删除文件
os.rmdir()删除单层目录,目录非空抛出异常
os.removedirs删除多层目录
os.rename(old,new)将文件old命名为new
os.system()运行系统的shell命令
os.walk(top)遍历top参数指定路径下的所有子目录,并将结果返回一个三元组(路径,[目录],[文件]
os.curdir指代当前目录
os.pardir指代上一级目录
函数名使用方法
os.path.basename()去掉目录路径,单独返回文件名
os.path.dirname()去掉文件名,单独返回目录路径
os.path.join(path1,path2…将各部分组合成一个路径名
os.path.split()分离文件名和路径,返回(f_path,f_name)元祖
os.path.splitext()分离文件名和扩展名,返回(f_name,f_extension)元组
os.path.getsize()返回指定文件的尺寸,单位为字节
os.gatatime()返回指定文件最近访问的时间
os.getctime()返回指定文件的创建时间
os.getmtime()返回指定文件的最新修改时间 ,这些都是浮点型,可以用time 模块,如time.gmtime(os.getmtime())or time.localtime(os.getmtime()
os.sep输出操作系统特定的路径分隔符(windows下为’、‘,linux下为’\n’
os.linesep行终止符,’\r\n’下一次执行时自动分行,使格式更好看
os.path.exists()判断指定路径是否存在
os.path.isabs()判断指定路径是否为绝对路径
os.path.isdir()判断指定路径是否存在且是一个目录
os.path. isfile()判断指定路径是否存在且是一个文件
os.path.islink判断只当路径是否存在且是一个符号链接
os.path.samefile(path1,path2)判断两个路径是否指向同一个文件

setfault的用法:

>>> a={1:'小白'}
>>> a.setdefault('小黑',2)
2
>>> a.setdefault('小黄',2)
2
>>> a
{1: '小白', '小黑': 2, '小黄': 2}
>>> a.setdefault('小li',0)
0
>>> a
{1: '小白', '小黑': 2, '小黄': 2, '小li': 0}
>>> a.setdefault('小wang')
>>> a
{1: '小白', '小黑': 2, '小黄': 2, '小li': 0, '小wang': None}
>>> a.keys()
dict_keys([1, '小黑', '小黄', '小li', '小wang'])
>>> a.values()
dict_values(['小白', 2, 2, 0, None])
>>> for each in a:
	print(each,end='')

	
1小黑小黄小li小wang
>>> for each in a:
	print(each,a[each],end=',')

	
1 小白,小黑 2,小黄 2,小li 0,小wang None,

编程题:

1:编写一个程序,统计当前目录下每个文件类型的文件数:

import os

all_files = os.listdir(os.curdir)
type_dict = dict()

for each_file in all_files:
    if os.path.isdir(each_file):
        type_dict.setdefault('文件夹',0)
        type_dict['文件夹']+=1
    else:
        ext = os.path.splitext(each_file)[1]
        type_dict.setdefault(ext,0)
        type_dict[ext]+=1

for each_type in type_dict.keys():
    print('该文件夹下共有类型为[%s]的文件%d个'%(each_type,type_dict[each_type]))

2:编写一个程序,计算当前文件夹下所有文件的大小:

import os

def file_size():
    file_name = os.listdir(os.curdir)
    dict1={}#or  dict1=dict()
    for each in file_name:
        if os.path.isfile(each):
            dict1.setdefault(each,os.path.getsize(each))
            print('%s的大小为:【%d Bytes】'%(each,dict1[each]))

file_size()

3:编写一个文件,用户输入文件名以及开始搜索的路径,搜索文件是否存在,如遇到文件夹,则进入文件夹继续搜索:

import os

def file_search(start_dir,target):
    os.chdir(start_dir)#修改当前路径

    for each_file in os.listdir(os.curdir):
        if each_file == target:
            print(os.getcwd()+os.sep+each_file)#os.sep使格式更好看
        if os.path.isdir(each_file):
            file_search(each_file,target)
            os.chdir(os.pardir)#一定注意要返回上一级目录

start_dir = input('请输入要查照的目录:')
target = input('请输入要查找的目标文件:')
file_search(start_dir,target)

4:编写一个程序,用户输入开始搜索的路径,查找改路径下(包括子文件在内的所有视频格式文件(mp4,rmvb,avi)并创建文件(filelist)存放所有找到的文件的路径。

import os
file_list = []
def file_search(start_dir):
    os.chdir(start_dir)

    for each in os.listdir(os.curdir):
        if os.path.isfile(each):
            a=os.path.splitext(each)[1]
            if  a == '.mp4'or a == '.rmvb'or a=='.avi':
                file_list.append(os.getcwd()+os.sep+each+os.linesep)
        if os.path.isdir(each):
            file_search(each)
            os.chdir(os.pardir)
    return file_list

start_dir=input('请输入有查找的目录:')
file_list=file_search(start_dir)
f=open(os.getcwd()+os.sep+'filelist.txt','wt',encoding='utf-8')
f.writelines(file_list)
f.close()

5:编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符):

import os

def search_file(key,start_dir):
    txt_file = []
    os.chdir(start_dir)
    all_files = os.walk(os.curdir)
    for i in 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_file.append(each_file)

    for each_txt in txt_file:
        key_dict = pos_in_file(key,each_txt)
        if key_dict:
            
            keys = key_dict.keys()
            keys = sorted(keys)
            for each_key in keys:
                print('关键字出现在第%s行,第%s个位置。'%(each_key,str(key_dict[each_key])))
        else:
            print('无关键字出现')

def pos_in_line(key,line):
    pos=[]
    begin=line.find(key)
    while begin!=-1:
        pos.append(begin+1)
        begin = line.find(key,begin+1)
    return pos
    

def pos_in_file(key,filename):
    key_dict={}
    count=0
    f=open(filename)
    for eachline in filename:
        count+=1
        if key in eachline:
            pos = pos_in_line(key,eachline)
            key_dict[count]=pos

    f.close()
    return key_dict

start_dir = input('请输入有查找的目录:')           
key = input('请输入关键字:')
search_file(key,start_dir)

pickle:

以下问答来自网络:

0.pickle的实质是什么?

pickle的实质就是利用一些算法将你的数据对象“腌制”成二进制文件,存储在磁盘上,当然也可以放在数据库或者通过网络传输到另一台计算机上。

1.使用pickle的什么方法存储数据?

pickle.dump(data, file) # 第一个参数是待存储的数据对象,第二个参数是目标存储的文件对象,注意要先使用’wb’的模式open文件哦。

2.使用pickle的什么方法读取数据?

pickle.load(file) # 参数是目标存储的文件对象,注意要先使用’rb’的模式open文件哦。

3.使用pickle能不能保存".txt"类型的文件?

可以,不过打开后是乱码,因为是以二进制的模式写入的。

用此方法小改文件的编程题补充:

import pickle
def file_save(carrot,melon,count):
    filename_carrot = 'D:\\'+'小萝卜'+str(count)+'.txt'
    filename_melon = 'D:\\'+'小西瓜'+str(count)+'.txt'
    file_carrot = open('%s'%filename_carrot,'wb')
    file_melon = open('%s'%filename_melon,'wb')
    pickle.dump(carrot,file_carrot)
    pickle.dump(melon,file_melon)
    file_carrot.close()
    file_melon.close()

def file_split(filename):
    f=open(filename,'rt',encoding='utf-8')
    carrot = []
    melon = []
    count = 1
    for each_line in f:
        if each_line[:4] != '====':
            (role,dialogue)=each_line.split(':',1)
            if role == '小萝卜':
                carrot.append(dialogue)
            if role == '小西瓜':
                melon.append(dialogue)
        else:
            file_save(carrot,melon,count)
            count+=1
            carrot = []
            melon = []
    file_save(carrot,melon,count)
    f.close()
    
filename = input('请输入文件名:')
file_split(filename)        

保存的文件结果是乱码的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值