0
点赞
收藏
分享

微信扫一扫

Python的学习(十六):对文件的操作

杨沐涵 2022-02-23 阅读 135

Python的学习(十六):对文件的操作

编码格式的介绍

  • Python中的解释器使用的是Unicode(内存)
  • .py文件在磁盘上使用UTF-8存储(外存)

image-20220208213456811

如何修改文件格式?不写的话默认为UTF-8

在python文件上面加上encoding = XXX

比如:

image-20220208213953503

文件读写的原理

image-20220209145038748

  • 内置函数open()创建文件对象

    image-20220209145351671

  • 语法规则

    file = open(filename [,mode,endcoding])

    image-20220209145551492

#创建时间:2022/2/9 14:58
#今日幸运数:5809

file = open('hello.txt','r',encoding = 'UTF-8')
print(file.readlines())
file.close()

image-20220209150933588

常用文件打开方式

文件的类型

  • 按照文件中数据的表现形式,文件分为以下两大类
    1. 文本文件:存储的是普通“字符”文本,默认为unicode字符集,可以使用记事本程序打开。
    2. 二进制文件:把数据内容用“字节”进行存储,无法用记事本打开,必须使用专门的软件打开,比如:MP3文件,jpg图片等
打开模式描述
r以只读方式打开文件,文件的指针会放在文件的开头
w以只读模式打开文件,如果文件不存在则创建,如果文件存在,则覆盖原有的内容,文件指针在文件的开头
a以追加模式打开文件,如果文件不存在则创建,文件指针在文件开头,如果文件存在,则在文件末尾追加内容,文件指针在原文件末尾
b以二进制方式打开文件,不能单独使用,需要与其它模式一起使用,rb或者rw
+以读写方式打开文件,不能单独使用,需要与其他模式一起使用,a+
file = open('a.txt','w')
file.write('我就想一直一直这样的喜欢你~')
file.close()

scr_file = open('hello.png','rb')
target_file = open('hello1.png','wb')
target_file.write(scr_file.read())

target_file.close()
scr_file.close()

文件对象的常用方法

  • 文件对象的常用方法
方法名说明
read([size])从文件中读取size个字节或字符的内容返回。若省略[size],则读取到文件末尾,即一次读取文件所有内容
readline()从文本文件中读取一行内容
readlines()把文本文件中每一行都作为独立的字符串对象,并将这些对象放入列表返回
write(str)将字符串str内容写入文件
writelines(s_list)将字符串列表s_list写入文本文件,不添加换行符号
seek(offset[,whence])把文件指针移动到新的位置,offset表示相对于whence的位置:offset:为正往结束方向移动,为负往开始方向移动。whence不同的值代表不同含义:0:从文件头开始计算(默认值)1:从当前位置开始计算。2:从文件尾开始计算
tell()返回文件指针的当前位置
flush()把缓冲区的内容写入文件,但不关闭文件
close()把缓冲区的内容写入文件,同时关闭文件,释放文件对象相关资源
#read([size])
file = open('hello.txt','r')
print(file.read())

image-20220209210108162

可以设定读取的字符个数:

image-20220209210158076

#readlines()
file = open('hello.txt','r',encoding='UTF-8')
print(file.readlines())
#结果是一个列表

image-20220209210343124

file = open('c.txt','a')
file.write('hello')
#可以将列表中的数据写到文件
lst = ['hello','my','love']
file.writelines(lst)
file.close()
file = open('hello.txt','r')
#文件从第二个字符开始读起
file.seek(2)
file.tell()#17
print(file,read)
file.close()
file = open('d.txt','a')
file.write('hello')
file.flush()
file.write('world')
file.close()

With语句(上席文管理器)

  • with语句可以自动管理上下文资源,不论是什么原因跳出with块,都能确保文件正确的关闭,以此来达到释放资源的目的。

    with open('a.txt','r') as file:
            print(file.read)
     #这样可以不用写关闭
    

    image-20220209212445787

  • 原理类比:

    '''
    实现了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('show方法被调用了')
            
            
    #调用
    with MyCounter() as file:#相当于file=MyCountentMgr()
        file.show()
        
    #不管是否产生异常,exit方法都会被调用
    

    实现文件复制:

    with open('hello.png','rb') as scr_file:
        with open('copy.png','wb') as target_file:
            target_file.write(scr_file.read())
    

目录操作

  • os模块是python内置的与操作系统功能和文件系统相关的模块。该模块中的语句执行结果通常与操作系统有关,在不同的操作系统上运行,得到的结果可能不一样。
  • os模块与os.path模块用于对目录或文件进行操作
#os模块和操作系统相关的一个模块
import os
os.system('calc.exe')
#直接调用可执行文件
os.startfile('D:\\Softwareloading\\CloudMusic\\cloudmusic.exe')

os模块相关函数

函数说明
getcwd()返回当前工作目录
listdir(path)返回指定路径下的文件和目录信息
mkdir(path[,mode])创建目录
makedirs(path1/path2…[,mode])创建多级目录
rmdir(path)删除目录
removedirs(path1/path2…)删除多级目录
chdir(path)将path设置为当前工作目录
import os
print(os.getcwd())#获取当前目录

lst = os.listdir('../chap1')
print(lst)

os.mkdir('newdir2')
os.makedirs('A/B/C')

os.rmdir('newdir2')
os.removedirs('A/B/C')

os.chdir('D:\\WorkPlace\\PyCharm\\MyPython\\chap1')

os.path模块操作目录相关函数

函数说明
abspath(path)用于获取文件或目录的绝对路径
exists(path)用于判断文件或目录是否存在,如果存在返回True,否则返回False
join(path,name)将目录名或者文件名拼接起来
splitext()分离文件名和扩展名
basename(path)从一个目录中提取文件名
dirname(path)从一个路径中提取文件路径,不包括文件名
isdir()判断是否为路径
import os.path
print(os.path.abspath('demon01.py'))
print(os.path.exists('demon13.py'))
print(os.path.join('E:\\Python','demon02.py'))
#将目录与文件拆分
print(os.path.split('D:\\WorkPlace\\PyCharm\\MyPython\\chap1\\demon03.py'))
#将文件库名和扩展名拆分
print(os.path.splitext('demon03.py'))#('demon13','.py')
print(os.path,basename('E:\\python\\chap15\\demon04.py'))#demon04.py
print(os.path,dirname('E:\\python\\chap15\\demon04.py'))#E:\python\chap15
print(os.path,isname('E:\\python\\chap15\\demon04.py'))#False
  • 列出指定目录下的所有py文件
import os
path = os.getcwd()
lst = os.listdir(path)
for filename in lst:
    if filename.endswith('.py'):
        print(filename)
  • 类似递归地列出文件
import os
path = os.getcwd()
lst_file = os.walk(path)
for dirpath,dirname,filename in lst_files:
    print(dirpath)
    print(dirname)
    print(filename)
    print('-------------------')
    
    
    #详细列出
    for dir in dirname:
        print(os.path.join(dirpath,dir))
        
    for file in filename:
        print(os.path.join(dirpath,file))
    print('--------------------') 

总结

image-20220210003735007

举报

相关推荐

0 条评论