4.1 文件基本操作
f = open('a.txt',mode='r',encoding='utf-8')
f.read()
f.close()
4.2 打开模式
-
r/w/a
-
r+/w+/a+
-
rb/wb/ab
-
r+b/w+b/a+b
4.3 操作
-
read(读取全部)
-
read(1) --> R模式下读取光标后一个字符
--> rb模式下读取光标后一个字节
#二进制模式下
obj = open('a.txt',mode='rb')
data = obj.read(3) # 1个字节
obj.close() -
-
write()写入
obj = open('a.txt',mode='r',encoding='utf-8')
obj.seek(3) # 跳转到指定字节位置
data = obj.read()
obj.close()
print(data)
obj = open('a.txt',mode='rb')
obj.seek(3) # 跳转到指定字节位置
data = obj.read()
obj.close()
print(data)flush()强制内存中的数据写入到硬盘
v = open('a.txt',mode='a',encoding='utf-8')
while True:
val = input('请输入:')
v.write(val)
v.flush()
v.close()tell() 获取光标当前所在字节位置
obj = open('a.txt',mode='rb')
# obj.seek(3) # 跳转到指定字节位置
obj.read()
data = obj.tell()
print(data)
obj.close()
4.4 关闭
一般方式:f.close()
特殊方式:with open("a.txt",mode='r',endcoding='utf-8') as v:
data = v.read() #缩进中的代码完成后自动关闭
4.5 文件内容的修改
with open("a.txt",mode="r",endcoding="utf-8") as v:
data = v.read()
new_data = data.replace("贪玩","蓝月")
with open('b.txt',mode='w',endcoding='utf-8') as v2:
data = v2.write(new_data)
4.5.1大文件的修改
with open('a.txt',mode='r',encoding='utf-8') as f1, open('c.txt',mode='w',encoding='utf-8') as f2:
for line in f1:
new_line = line.replace('渣渣辉', '陈咬春')
f2.write(new_line)