打开读写文件:
f=open("yesterday2",'r',encoding="utf-8") ##打开文件名称,r读模式,字符类型
date=f.read() ##把读值赋给date
print(date)
f.close() ##文件关闭
d=open("yesterday4",'w',encoding="utf-8") ##打开文件名称,w写(重新创建覆盖之前),字符类型
d.write("abc,\ndef\tzxc!")
##date=d.read() w模式不能读取
d.close()
c=open("yesterday4",'a',encoding="utf-8") ##打开文件名称,a=append 追加,字符类型
c.write("asd\tqwe")
##date2=c.read() ##不能读
c.close()
f=open("yesterday2",'r',encoding="utf-8") ##打开文件名称,r读模式,字符类型
print(f.readline()) ##读取第一行
for i in range(5): ##读取前五行
print(f.readline())
for line in f.readlines(): ##把每段的内容分行读取
print(line.strip()) ##去掉空格换行
count = 0
for line in f: ##效率最高占用内存小打印前10行
if count ==9:
print("-----------------------")
count +=1
continue
print(line)
count +=1
print(f.tell()) ##查询打开文件光标位置
f.seek(0) ##退回到文件最开头
print(f.flush()) ##将写的内容实时刷新在硬盘上
f.truncate(20) ##从头开始截断
f=open("yesterday2",'r+',encoding="utf-8") ##打开文件名称,r+读写模式只能追加在最后,字符类型
f=open("yesterday2",'w+',encoding="utf-8") ##打开文件名称,W+写读模式只能追加在最后,字符类型
f=open("yesterday2",'a+',encoding="utf-8") ##打开文件名称,a+追加读模式只能追加在最后,字符类型
f=open("yesterday2",'rb') ##以二进制格式打开
进度条:
import sys,time
for i in range(20): ##进度条
sys.stdout.write("#")
sys.stdout.flush() ##刷新
time.sleep(0.1) ##延迟打印
文件修改:
f = open("yesterday2","r",encoding="utf-8")
f_new = open("yesterday2.bak","w",encoding="utf-8")
for line in f: ##以行循环f
if "为了昨日" in line: ##判断字符串在此行
line = line.replace("为了昨日","为了今日") ##替换此字符串
f_new.write(line) ##将line循环写入f_new
f.close()
f_new.close()