# 1.数据持久化(数据本地化)# 默认情况下程序中所有的数据都是保存在运行内存中的,运行内存中的数据在程序运行结束后会自动销毁。# 只要将数据存储在硬盘中,数据才会一直存在。# 如果想要将程序中产生的数据保存到硬盘中,需要先将数据存储到文件中。(常见的文件:数据库文件、plist文件、json文件、txt文件..)# 2.文件操作 - 操作文件中的内容# 基本步骤:打开文件 -> 操作文件(读、写) -> 关闭文件# 2.1 打开文件"""
open(file, mode='r',*,encoding=None) - 打开文件并且返回一个文件对象
1) file - 需要打开的文件的路径(地址)
a.绝对路径:文件或者文件夹在计算机中的全路径
例如:/Users/yuting/授课/Python2101/01语言基础/day13-常用模块和文件操作/files/test.txt
b.相对路径:写路径的时候只写全路径的一部分,剩下的部分用特殊符号代替
. - 表示当前目录(当前代码文件所在的目录),可以省略
.. - 表示当前目录的上层目录
... - 表示当前目录的上层目录的上层目录
2) mode - 文件打开方式(决定打开文件后能做什么、操作文件的时候对应的数据类型)
第一组值:决定打开后能做什么,读/写?
r - 只读
w - 只写,打开后会清空源文件中的内容
a - 只写,打开后不会清空源文件内容
第二组值:决定操作文件数据的时候对应的数据类型,字符串/二进制?默认是 t
t - 文本数据,对应的类型是str(默认)
b - 二进制数据,对应的类型是bytes
两组数据中必须每一组选择一个值:'r' == 'rt'、'tr'、
格式:'wb'、'bw'
3)encoding - 设置文本文件的编码方式,一般设置成utf-8
如果是以t的形式打开一个文本文件的时候需要设置encoding。
打开方式带b绝对不能设置encoding
"""# 绝对路径open(r'/Users/yuting/授课/Python2101/01语言基础/day13-常用模块和文件操作/files/test.txt')# 相对路径open(r'./files/test.txt')open(r'./aaa.txt')open(r'../day13-常用模块和文件操作/files/test.txt')# r - 只读
f =open(r'./files/test.txt','r')
f.read()
f.write('abc')# io.UnsupportedOperation: not writable# a - 只写
f =open(r'./files/test.txt','a')
f.write('abc')
f.read()# io.UnsupportedOperation: not readable# w - 只写,清空
f =open(r'./files/test.txt','w')
f.write('xyz')
f.read()# io.UnsupportedOperation: not readable# t/b - 操作数据是字符串
f =open(r'./files/test.txt','rb')
result = f.read()print(result,type(result))
f =open(r'./files/test.txt','ab')
f.write('abc')# TypeError: a bytes-like object is required, not 'str'
f.write('123abc123'.encode())# 注意:打开二进制文件必须带 b
f =open(r'files/luffy4.jpg','rb')
f.read()# r和a、w打开不存在的文件 - r会报错;w和a不报会新建open(r'./files/bbb.txt','r')# FileNotFoundErroropen(r'./files/ccc.txt','a')# 2.2 读写文件# 1) 读:# a.文件对象.read() - 从读写位置开始读到文件结束(结束的时候读写位置在文件末尾)
f =open('files/test.py','rt', encoding='utf-8')
result = f.read()print(result)print('=======================')
f.seek(0)# 将读写位置设置到文件开头
result = f.read()print(result)# b.文件对象.readline() - 从读写位置开始到一行的末尾(只有针对以t打开的文本文件)
f =open('files/test.py','rt', encoding='utf-8')
result = f.readline()print(result)
result = f.readline()print(result)print('========================')
result = f.read()print(result)# 2) 写# 文件对象.write(数据)
f =open(f'files/test.py','a', encoding='utf-8')
f.write('\nprint("hello world")')# 2.3 关闭文件# 文件对象.close()
f.close()
f.write('ksskskksk')# ValueError: I/O operation on closed file.
五、二进制与字符之间的转换
# 1.字符串(str)转二进制(bytes)# 方法一:bytes(字符串,encoding='utf-8')
result =bytes('护士', encoding='utf-8')print(result)#方法二:字符串.encode()
result ='护士'.encode()print(result,type(result))# 2.二进制转字符串# 方法一:str(二进制,encoding='utf-8')
s =str(result,encoding='utf-8')print(s,type(s))# 方法二:二进制.decode()
s = result.decode()print(s)