f = open("yesterday", 'r', encoding="utf-8") # 文件句柄
print(f.tell()) #打印当前的位置
print(f.readline()) #打印一行
print(f.readline()) #打印一行
print(f.readline()) #打印一行
print(f.tell()) #打印当前的位置
f.seek(0) #光标回到哪个地方
print(f.readline()) #打印一行
print(f.encoding) #打印文件的编码
进度条:
import sys,time
for i in range(20):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.1)
f = open("yesterday", 'a', encoding="utf-8") # 文件句柄
f.truncate(10) #从头开始截10个
r+ 是读写
f = open("yesterday", 'r+', encoding="utf-8") # r+是读写
print(f.readline())
print(f.readline())
print(f.readline())
f.write("--------diao--------")
print(f.readline())
rb 用二进制形式读文件
使用场景:
1. 网络传输,只能用二进制模式传输
2. 用二进制模式打开视频
f = open("yesterday", 'rb') # 用二进制形式读文件
print(f.readline())
print(f.readline())
print(f.readline())
wb 用二进制形式写文件
f = open("yesterday", 'wb') # 用二进制形式写文件,它内部是用二进制格式的
f.write("hello binary\n".encode())
f.close()
文件修改:
注:yesterday是原文件,yesterday2是新的空文件
f = open("yesterday","r",encoding="utf-8")
f_new = open("yesterday2","w",encoding="utf-8")
for line in f:
if "肆意的快乐等我享受" in line:
line = line.replace("肆意的快乐等我享受","肆意的快乐等zhuziqin享受")
f_new.write(line)
f.close()
f_new.close()
with语句: 帮你自动关闭文件
with open("yesterday","r",encoding="utf-8") as f:
for line in f:
print(f.readline())