美文网首页
2021-09-21-P126--P132-文件读写-马士兵Py

2021-09-21-P126--P132-文件读写-马士兵Py

作者: FFwizard | 来源:发表于2021-09-21 23:11 被阅读0次

    2021-09-17

    视频链接

    课程介绍

    1、编码格式介绍
    2、文件的读写原理
    3、文件读写操作
    4、文件对象常用的方法
    5、with语句()上下文管理器)
    6、目录操作

    126、编码格式

    常见的字符编码格式

    python的解释器使用的是Unicode
    .py文件在磁盘上使用UTF-8存储


    image.png

    在代码开头使用#encoding=解释器,更改默认解释器

    127、文件的读写原理_读取磁盘的内容

    文件的读写俗称“IO”操作
    文件读写操作流程
    操作原理
    .py→解释器→OS→操作→硬盘
    python操作文件→打开或新建文件→读、写文件→关闭资源。

    文件的读写操作

    内置函数open()创建文件对象
    file=open(filename【,mode,encoding】)
    file:被创建的对象
    open:创建文件对象的函数
    filename:要创建或打开耳朵文件名称
    mode:打开默认模式认为只读
    默认文本文件中字符的编写格式为gbk

    ##127、文件的读写原理_读取磁盘的内容
    file=open('a.txt','r',encoding='UTF-8')  #以读的方式
    print(file.readline())
    file.close()
    

    128、文件的读写原理_常用文件的打开模式

    file=open('b.txt','w')  # 不存在会新创建,存在会覆盖
    file.write('python')
    file.close()
    
    file=open('b.txt','a')  # 不存在会新创建,存在追加模式在原有的文件添加
    file.write('python')
    file.close()
    
    src_file=open('logo.png','rb')  # b 二进制方式打开文件,需要与r、w连用
    target_file=open('copylogo.png','wb')
    print(target_file.write(src_file.read()))
    target_file.close()
    src_file.close()
    

    129、文件的读写原理_文件对象的常用方法

    ##129、文件的读写原理_文件对象的常用方法
    file=open('a.txt','r',encoding='UTF-8')  #以读的方式打开文件
    print(file.read())  # 读取文档所有内容
    print(file.readline())  # 读取文档一行内容
    print(file.readlines())  # 读取文档一行内容,作为列表输出
    
    file=open('c.txt','a')  #以读的方式打开文件 a追加
    lst=['java','go','python']
    file.writelines(lst) # 写入一个列表
    file.close()
    
    file=open('a.txt','r',encoding='UTF-8')
    file.seek(8)  ##文件指针移动到新的位置
    print(file.read())
    file.close()
    
    file=open('c.txt','r')
    file.seek(2)  ##文件指针移动到新的位置
    print(file.read())
    print(file.tell()) #返回文件指针的当前位置
    file.close()
    
    file=open('d.txt','a')
    file.write('hello')
    file.flush() #把缓冲区的内容写入文件,但不关闭文件
    file.write('world')
    file.close()
    

    130、with语句(上下文管理器)

    with语句可以自动管理上下文资源,不论什么原因跳出with块,都能确保文件正确的关闭,以此来达到释放资源的目的。
    with open('a.txt','r',encoding='UTF-8') as file:
    print(file.read())
    open('a.txt','r',encoding='UTF-8') 为上下文表达式,其对象为上下文管理器

    ##130、with语句(上下文管理器)
    with open('a.txt','r',encoding='UTF-8') as file:
        print(file.read())
    
    '''MyContentMgr实现了特殊方法__enter__和__exit__称为该类对象遵守了上下文管理器协议
    该类对象的实力对象,称为上下文管理器
    '''
    class MyContentMgr(object):
        def __enter__(self):
            print('enter方法被调用执行了')
            return self
    
        def __exit__(self,exc_type,exc_val,exc_tb):
            print('exit方法被调用实行了')
    
        def show(self):
            print('exit方法被调用执行了',1/0)
    with MyContentMgr() as file:   #相当于file = MyContentMgr
        file.show()
    
    ####with 操作文件不需要关闭文件
    with open('logo.png','rb') as src_file:
        with open('copy2logo.png','wb') as target_file:
            target_file.write(src_file.read())
    

    131、OS模块的常用操作

    Osi模块是Python内置的与操作系统功能和文件系统相关的模块,该模块中的语句的执行结果通常与操作系统有关,在不同的操作系统上运行,得到的结果可能不一样。
    OS模块与OS.path模块用于对目录或文件进行操作

    OS 模块操作目录相关函数
    image.png

    getcwd():返回当前工作目录
    listdir(path)

    ##131、OS模块的常用操作
    import os
    #os.system('calc.exe') #调用系统程序
    os.system("C:\\Program Files (x86)\\Tencent\\QQ\\Bin\\QQ.exe")  #直接调用可执行文件
    #
    os.getcwd()  #返回当前的工作目录
    os.listdir('../mashibing')  ##返回指定路径下的文件和目录信息
    os.mkdir('newdir')  ##创建目录
    os.makedirs('A/B/C')  #创建多级目录
    os.rmdir('newdir')  #删除目录
    os.removedirs('A/B/C')  #删除多级目录
    os.chdir('C:\\Users\\Wizard\\PycharmProjects\\pythonProject\\mashibing') #将path设置为当前工作目录
    

    132、OS模块操作目录相关函数

    ##132、OS模块操作目录相关函数os.path
    import os.path
    print(os.path.abspath('chap14')) ##输出绝对路径
    print(os.path.exists('chap14'))  #判断文件是否存在
    print(os.path.join('C:\\Users\\Wizard\\PycharmProjects\\pythonProject\\mashibing\\','chap14'))  #拼接路径
    print(os.path.split('C:\\Users\\Wizard\\PycharmProjects\\pythonProject\\mashibing\\chap14'))  #将目录与文件进行拆分
    print(os.path.splitext('chap14\\scratch\\calc.py')) #拆分文件名和后缀名
    print(os.path.basename('C:\\Users\\Wizard\\PycharmProjects\\pythonProject\\mashibing'))  #从一个目录中提取文件名
    print(os.path.dirname('C:\\Users\\Wizard\\PycharmProjects\\pythonProject\\mashibing'))  #提取目录
    print(os.path.isdir('C:\\Users\\Wizard\\PycharmProjects\\pythonProject\\mashibing'))  #判断是否为目录
    
    ###题目:列出文件下的所有py文件
    import os
    path=os.getcwd()
    lst=os.listdir(path)
    for filename in lst:
        if filename.endswith('.py'):
            print(filename)
        if os.path.splitext(filename)[1]=='.py':
            print(filename)
    
    ###题目:列出文件下及所有子文件下的的所有py文件
    import os
    os.chdir('C:\\Users\\Wizard\\PycharmProjects\\pythonProject\\mashibing\\chap14') #将path设置为当前工作目录
    path=os.getcwd()
    lst_files=os.walk(path) #遍历文件下的所有子文件
    print(lst_files) #返回的元祖
    for dirpath,dirname,filename in lst_files:
        '''print(dirpath)
        print(dirname)
        print(filename)'''
        for dir in dirname:
            print(os.path.join(dirpath,dir))  ##输出所有子文件夹的绝对路径
        for file in filename:
            print(os.path.join(dirpath,file))  ##输出所有子文件的绝对路径
    
    lst=os.listdir(path)
    for filename in lst:
        if filename.endswith('.py'):
            print(filename)
        if os.path.splitext(filename)[1]=='.py':
            print(filename)
    

    相关文章

      网友评论

          本文标题:2021-09-21-P126--P132-文件读写-马士兵Py

          本文链接:https://www.haomeiwen.com/subject/yztwgltx.html