1.打开文件
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
打开文件的模式
- r,只读模式【默认】
- w,只写模式,不存在则新建,存在则删除内容
- a,追加模式,不存在则新建,存在则追加内容
f = open('yesterday.txt','a',encoding='utf-8') #可写,不存在则新建
print(f.write('\n庆余年'))
f.close()
f = open('yesterday.txt','r',encoding='utf-8') #只读
print(f.read())
f.close()
f = open('yesterday.txt','w',encoding='utf-8') #只写,打开文件内容为空,相当于新建
print(f.write('20191220'))
f.close()
运行结果
4
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
庆余年
8
"+" 表示可以同时读写
- r+,可读,可写,可追加,不建议修改【见案例1&2】
- w+,可写,可读
- a+,同a
案例1:
f = open('yesterday.txt','r+',encoding='utf-8') #可读,可写
print(f.read())
print('-----------分隔符------------')
f.write('梦回大清')
f.seek(0)
print(f.read())
f.close()
运行结果:
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
-----------分隔符------------
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种梦回大清
案例2:跟案例1区别只屏蔽了一条语句
f = open('yesterday.txt','r+',encoding='utf-8') #可读,可写
#print(f.read()) #与案例1的区别
print('-----------分隔符------------')
f.write('梦回大清')
f.seek(0)
print(f.read())
f.close()
运行结果:
-----------分隔符------------
梦回大清seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,with又支持同时对多个文件的上下文进行管理,如:
with open('log1') as obj1, open('log2') as obj2:
pass
with open('yesterday.txt','a+',encoding='utf-8') as f: #可读,可写
f.write('\n啦啦啦') #追加
f.seek(0)
print(f.read()) #当with代码块执行完毕时,内部会自动关闭并释放文件资源
运行结果:
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
啦啦啦
2.文件迭代
1.readline&readlines
with open('yesterday.txt','r+',encoding='utf-8') as f: #可读,可写
s = f.readline() #readline返回类型是字符串
print(s,type(s))
s = f.readlines() #readlines返回类型是列表
print(s,type(s))
运行结果:
one
<class 'str'>
['two\n', 'three\n', 'four\n', 'five\n', 'six\n', 'seven\n', 'eight\n', 'nine\n', 'ten'] <class 'list'>
2.迭代
比较low的迭代,速度慢,占内存
with open('yesterday.txt','r+',encoding='utf-8') as f: #可读,可写
for line in f.readlines():
print(line.strip('\n'))
记住这种,效率高,不占内存,大文件。
with open('yesterday.txt','r+',encoding='utf-8') as f: #可读,可写
for line in f:
print(line.strip('\n'))
3.光标移动
我们将文件都视为流,只能按顺序从头读到尾读取,实际上,可在文件中移动,只访问感兴趣的部分。可使用方法:seek,tell
with open('yesterday.txt','r+',encoding='utf-8') as f: #可读,可写
f.read() #光标移动到结果
print(f.tell())
f.seek(0) #移动到开头
print(f.tell())
f.read(5)
print(f.tell()) #打印光标位置
运行结果:
57
0
6
flush强制刷新
为了防止意外,需要强制刷新,保存文件。
for i in range(30):
sys.stdout.write('#')
sys.stdout.flush()
time.sleep(0.2)
修改文件
修改文件时,最好新建一个文件,存放修改后的内容,可以防止文件丢失。
with open('yesterday.txt','r',encoding='utf-8') as f,\
open('yesterday2.bak','w',encoding='utf-8') as f_new:
for line in f:
if '年少轻狂' in line:
line = line.replace('年少轻狂','“年少轻狂不自卑”')
f_new.write(line)