r=open("db","r")

f.close()

r读出来的是字符串

rb读出来的是字节

w=open("db","wb")

w.write(bytes("中国",encoding=“utf-8”))

w.close()

r+

w+

a+

x+

二进制的是:

r+b

x+b

w+b

a+b

f=open("db","r+",encoding="utf-8")
data=f.read()#只要一读就放到末尾了
print(data)
print(f.tell())
f.seek(f.tell())
f.write("888")
f.close()f=open("db","r+",encoding="utf-8")data=f.read()print(data)f.seek(1)#指针定位到1之后写入后的话会覆盖后面的内容f.write("777b")f.close()#r+这个写的是继续在原来文件后面开始写的

f=open("db","r+",encoding="utf-8")
data=f.read()#只要一读就放到末尾了
print(data)
f.write("中国")
f.close()
#以上如果无b则 按照字符来读取 tell当前指针所在的位置,而seek调整当前指针的位置
写的时候是从当前指针位置向后覆盖

#a+的话每次写入都自动弄到文件的最后一个位置了而w+就会把原来的内容都清空掉了r+是最常用的.如果不用seek 则默认写到文件的最后
#read 无参数读全部,如果有b按照字节,如果没有b 则按照字符

#write 跟打开方式有关系,如果打开方式有b 则你只能写字节,如果无b 则写字符
flush 强刷新,


f=open("db","r+",encoding="utf-8")#a+的话每次写入都自动弄到文件的最后一个位置了而w+就会把原来的内容都清空掉了
f.write("123")
f.flush()#强刷,将数据弄到文本里面
input("fs")f.readline()#仅仅读取一行
指针在移动
f=open("db","r+",encoding="utf-8")#a+的话每次写入都自动弄到文件的最后一个位置了而w+就会把原来的内容都清空掉了
print(f.tell())
data=f.read()#只要一读就把指针弄到文本的最后了
f.write("123")
f.flush()#强刷,将数据弄到文本里面
f.seek(3)
f.truncate()#把指针三后面的东西全部干掉
f.close()#这个模式是以后最最常用的
f=open("db","r+",encoding="utf-8")
for line in f:
print(line)


#读取文件然后写入另一个文件

with open("db","r") as f1,open("db2","w") as f2:
count=0
for line in f1:
count+=1
if count<=10:
f2.write(line)
else:
break
with open("db","r") as f1,open("db2","w") as f2:
count=0
for line in f1:
count+=1
if "Alex" in line:
new_line=line.replace("Alex","fffffffffffffffff")
if count<10:
f2.write(new_line)
else:
break