open()
用于打开一个文件,并返回file文件对象,如果文件无法打开则抛出异常OSError
使用完open()方法,要关闭文件对象,close()方法
语法格式:open(file, mode='r', buffering=-1,encoding=None,errors=None,newline=None,closefd=True, opener=None)
- file :必需,文件路径
- mode :可选,文件打开模式,'t’默认文本模式、'r’只读模式、'w’覆盖写、'a’追加写、'r+'同时读写、 'b’二进制模式
- buffering :设置缓冲
- encoding :一般utf-8
- errors :错误级别
- newline :区分换行符
- closefd :传入的file参数类型
获取file对象:f = open(file, mode='r')
f = open('test.txt', 'r', encoding='utf-8')
输出
<_io.TextIOWrapper name='test.txt' mode='r' encoding='utf-8'>
常用属性:
- f.closed 检查文件是否打开
- f.encoding 返回文件字符编码
- f.name 返回文件名
f = open('test.txt', 'r', encoding='utf-8')
print('文件是否打开:', f.closed)
print('文件字符编码:', f.encoding)
print('文件名:', f.name)
输出:
文件是否打开: False
文件字符编码: utf-8
文件名: test.txt
常用方法:
- 读文件:
f = open(file, mode=‘r’)
f.read() 读取文件内容,返回字符串形式
f.readline() 读取文件的一行内容,如果返回一个空字符串, 说明已经已经读取到最后一行。
f.readlines() 读取文件内容返回为列表形式,每行内容为列表一个元素
# text.txt
第一行内容
第二行内容
第三行内容
f1 = open('test.txt', 'r', encoding='utf-8')
f2 = open('test.txt', 'r', encoding='utf-8')
f3 = open('test.txt', 'r', encoding='utf-8')
print(f1.read())
print('/')
print(f2.readline())
print('/')
print(f3.readlines())
输出:
第一行内容
第二行内容
第三行内容
/////////////
第一行内容
/////////////
['第一行内容\n', '第二行内容\n', '第三行内容']
- 写文件:
f = open(file, mode=‘w’)
f.write(s) 将字符串写入文件,返回字符数
f.writeline(iter) 将一个可迭代对象的所有元素写入文件
f = open('test.txt', 'w', encoding='utf-8')
print('返回的字符数:', f.write('写入内容'))
输出:
返回的字符数: 4
- f.close()
关闭释放资源 - with…as …语句
管理上下文,可实现打开文件后自动关闭
with open('test.txt', 'w', encoding='utf-8') as f:
print('返回的字符数:', f.write('写入内容'))
print("是否关闭:", f.closed)
输出:
返回的字符数: 4
是否关闭: True
pickle 模块
pickle 模块实现了基本的数据序列和反序列化,
- 序列化操作能够将程序中运行的对象信息保存到文件中去,永久存储
import pickle
data = {
'key1': [1, 2, 4, 6],
'key2: ('apple', 'banbana'),
'key3': None
}
output = open('data.pkl', 'wb')
pickle.dump(data, output)
output.closed
- 反序列化操作能够从文件中创建上一次程序保存的对象
import pickle
pkl_file = open('data.pkl', 'rb')
data = pickle.load(pkl_file)
print(data)
输出
{'a': [1, 2, 4, 6], 'b': ('string', 'Unicode string'), 'c': None}