【Python30--文件系统】

一、模块

定义:模块是一个包含所有定义的函数和变量的文件,后缀名是.py。模块可以被别的程序引用,以使用该模块中的函数等功能

>>> secret = random.randint(1,10)    #调用random里面的randint,1到10 的随机数
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    secret = random.randint(1,10)
NameError: name 'random' is not defined

---报错原因:random没有被定义,所以需要引入random
>>> import random
>>> secret = random.randint(1,10)
>>> secret
3

二、os模块:Operating System操作系统

os模块中关于文件,目录常用的函数使用方法

函数                使用方法

getcwd()              返回当前工作目录

chdir(path)             返回工作目录

listdir(path='.')            列举指定目录中的文件名(‘.’表示当前目录,‘.’表示上一级目录)

mkdir(path)              创建单层目录,如该目录已存在抛出异常

makedirs(path)           递归创建多层目录,如该目录已存在抛出异常,注意:'E:\a\b'和'E:\a\c'并不会冲突

remove(path)            删除文件

rmdir(path)             删除单层目录,如该目录非空则抛出异常

removedir(path)            递归删除目录,从子目录到父目录逐层尝试删除,遇到目录非空则抛出异常 

rename(old, new)          将文件old重名为new

system(command)           运行系统的shell命令

walk(top)             遍历top路径以下所有的子目录,返回一个三元组:(路径, [包含目录], [包含文件])

        以下是支持路径操作中常用的一些定义,支持所有平台

os.curdir              指代当前目录(‘.’)

os.pardir              指代上一级目录('..')

os.sep               输出操作系统特定的路径分隔符(Win下为'\',Linux下为'/')

os.linesep              当前平台使用的行终止符(Win下为' ',Linux下为' ')

os.name              指代当前使用的操作系统(包括:'posix',  'nt', 'mac', 'os2', 'ce', 'java')

os.path模块中关于路径常用的函数使用方法

函数名               使用方法

basename(path)            去掉目录路径,单独返回文件名

dirname(path)             去掉文件名,单独返回目录路径

join(path1[,path2[,...]])        将path1,path2各部分组合成一个路径名

split(path)              分隔文件名与路径,返回(f_path,f_name)元组,如果完全使用目录,他也会将最后他一个目录作为文件名分隔,且不会判断文件或者目录是否存在

splitext(path)            分离文件名与扩展名,返回(f_name,f_extension)元组

getsize(file)              返回指定文件的尺寸,单位是字节

getatime(file)            返回指定文件最新的访问时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)

getctime(file)            返回指定文件的创建时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)

getmtime(file)             返回指定文件最新的修改时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)

            以下函数返回True或False

exists(path)             判断指定路径(目录或文件)是否存在

isabs(path)              判断指定路径是否我绝对路径

isdir(path)               判断指定路径是否存在且是一个目录

isfile(path)               判断指定路径是否存在且是一个文件

islink(path)              判断指定路径是否存在且是一个符号链接

ismount(path)            判断指定路径是否存在且是一个挂载点

samefile(path1,path2)         判断path1和path2两个路径是否指向同一个文件

三、练习题

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

思路:

1、首先找到需要查找文件的路径

2、定义一个空的字典,用于存查找到的文件

3、在整个路径内遍历循环

  --判断为文件夹时输出文件夹(知识点:isdir():判断文件是否存在)(另外一个知识点:setdefault())

  --判断为文件时输出文件的后缀(知识点:splitext():分离文件与扩展名)

---setdefault(key,default=None):

参数

  •     key -- 这是要被搜索的键
  •     default -- 这是没有找到键的情况下返回的值。

返回值

此方法返回字典可用的键值,如果给定键不可用,则它会返回所提供的默认值。


import os
"""
|-- os.listdir:列举指定目录中的文件
|-- os.curdir:表示当前目录更标准
"""

def type_file_key():
    all_file = os.listdir(os.curdir)
    file_dict = dict()

    for each_file in all_file:
        if os.path.isdir(each_file):#isdir:判断指定的文件是否存在
            file_dict.setdefault('文件夹',0)
            file_dict['文件夹'] += 1
        else:
            ext=os.path.splitext(each_file)[1]#splitext:分离文件名与路径,后面的[1]表示只分离一次
            file_dict.setdefault(ext,0)
            file_dict[ext] += 1

    # 遍历字典内的每一个key
    for each_type in file_dict.keys():
        print('该文件下共有类型为【%s】的文件%d个'%(each_type,file_dict[each_type]))

type_file_key()




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



mport os

def type_file_size():
    all_file = os.listdir(os.curdir)
    file_dict = dict()

    for each_file in all_file:
        if os.path.isfile(each_file): #isfile():判断路径下是否存在一个文件
            #getsize():返回文件的尺寸,单位是字节
            #字典里面去查询文件,默认返回文件大小
            file_dict.setdefault(each_file,os.path.getsize(each_file))
            print('文件【%s】的大小【%dBytes】'%(each_file,file_dict[each_file]))

type_file_size()


 
 3、编写一个程序,y用户输入文件名以及开始搜索的路径,搜索该文件是否存在,如遇到文件夹,则进入文件夹继续搜索
思路:
1、定义一个函数(包含两个参数:文件路径,文件)
2、遍历整个文件路径,如果存在文件就返回当前的路径+文件名;如果是一个文件夹就递归调用函数进行查找(注意点:递归调用后返回上一级目录)

import os

def search_file(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)
        #如果是个文件则进入文件再次查找文件(递归调用函数)
        if os.path.isdir(each_file):
            search_file(each_file, target)
            #返回上一层目录
            os.chdir(os.pardir)

start_dir = input('请输入需要查找的路径:')
target = input('请输入查找的文件:')
search_file(start_dir,target)


 
 4、输入开始搜索的路径,查找该路径下(包含子文件夹内)所有的视频格式文件(要求查找MP4,rmvp,avi的格式即可),并把创建一个文件(vedioList.txt)存放所有赵傲的文件的路径。

思路:1、查找指定路径下的视频格式 2、再把找到的视频文件路径存到一个TXT文件内


import os
def search_write_path(start_dir,target):
    os.chdir(start_dir)

    #遍历当前文件的列表数据
    for each_file in os.listdir(os.curdir):
        #splitext:分离文件名和拓展名
        ext = os.path.splitext(each_file)[1]

        if ext in target:
            void_list.append(os.getcwd()+os.sep+each_file+os.linesep)
        if os.path.isdir(each_file):
            search_write_path(each_file,target)

            os.chdir(os.pardir)

start_dir = input('请输入路径:')
target = ['.mp4','.rmvp','.avi']

program_dir = os.getcwd()
void_list =[]

search_write_path(start_dir,target)

f = open(program_dir+os.sep+'vedioList.txt','w')
f.writelines(void_list)
f.close()


 

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


 

import os

#打印关键字
def print_key(dict_key):
    keys = dict_key.keys() #keys():以列表返回一个字典所有的键
    keys = sorted(keys)  #字典是无序的,对字典内行数进行排序

    for each_key in keys:
        print('关键字在第【%s】行第【%s】个位置'%(each_key,str(dict_key(each_key))))

#行里面找关键字
def key_in_line(line,key):
    pos = []
    begin = line.find(key)

    while begin != -1:
        pos.append(begin+1)  #用户的角度从1开始
        begin = line.find(key,begin+1) #从下一个位置继续查找

    return pos

#文件内找行
def search_file_line(file_name,key):
    f = open(file_name)
    count = 0
    dict_key = dict()

    for each_line in f:
        count +=1
        for key in each_line:
            pos = key_in_line(each_line,key)
            dict_key[count]=pos

    f.close()
    return dict_key

#路径下找文件
def search_file(key,detail):
    all_files = os.walk(os.getcwd()) #os.walk():根目录下的每一个文件夹,产生3-元组 (dirpath, dirnames, filenames)【文件夹路径, 文件夹名字, 文件名】
    txt_file = []

    for i in all_files:
        #i[0]:dirpath,i[1]:dirnames,i[2]:filenames
        for each_file in i[2]:
            if os.path.splitext(each_file)[1]=='.txt':
                each_file = os.path.join(i[0],each_file) #os.path.join():将多个路径z组合后返回
                txt_file.append(each_file)

        for each_txt_file in txt_file:
            dict_key = search_file_line(each_txt_file,key)
            if dict_key:
                print('=========================================')
                if detail in ['YES','Yes','yes']:
                    print_key(dict_key)

key = input('请输入文件路径:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO)'%key)
search_file(key,detail)
原文地址:https://www.cnblogs.com/frankruby/p/9379058.html