“”"
读:r,rb,r+,r+b
写:w,wb,w+,w+b
加:a,ab,a+,a+b
tell():获取光标的位置
seek:调整光标的位置
flush:强制刷新
“”"
with open('1.txt', encoding = 'utf-8', mode = 'r')as f:
txt = f.read()
print(txt)
with open('1.txt', encoding = 'utf-8', mode = 'r')as f:
txt = f.read(6) # 只读取6个字符
print(txt)
with open('1.txt', encoding = 'utf-8', mode = 'r')as f:
txt = f.readline(6) # 只读取第一行的前6个字符
print(txt)
with open('1.txt', encoding = 'utf-8', mode = 'r')as f:
txt = f.readlines()
print(txt)
with open('1.txt', encoding = 'utf-8', mode = 'r')as f:
for txt in f:
print(txt)
with open('1.jpg', mode = 'rb')as f:
txt=f.read()
print(txt)
文件必须存在,不存在会报错
with open('1.txt', encoding='utf-8', mode='r+')as f:
f.write('11111111') # 文件必须存在,指针在开头写入并替换
with open('1.txt', encoding='utf-8', mode='r+')as f:
txt=f.read()
f.write('11111111') # 文件必须存在,指针在结尾写入
如果文件存在,先清空原内容,再写入新内容;如果文件不存在,会创建文件,并写入内容
with open('1.txt', encoding='utf-8', mode='w')as f:
f.write('新写入的文本内容')
with open('1.jpg', mode = 'wb')as f:
f.write(b'新写入的字符串(不能为汉字)') # 以二进制写入新内容
文件的追加a,ab,a+,a+b,没有文件,创建文件,追加内容,有文件在源文件的最后面加入内容
with open('1.txt', encoding='utf-8', mode='a')as f:
f.write('要追加的文本内容') #在结尾追加
with open('1.txt', encoding='utf-8', mode='a+')as f:
f.write('要追加的文本内容') # 在结尾追加
with open('1.jpg', mode = 'ab')as f:
f.write(b'要追加的字符串(英文或数字)') # 以二进制形式追加在文件的结尾
with open('1.txt', encoding='utf-8', mode='r+')as f:
print(f.tell()) # 光标位置在开头,为0
txt=f.read()
print(f.tell()) # 光标位置在结尾,为txt字符串长度
with open('1.txt', encoding='utf-8', mode='r+')as f:
f.seek(8)
f.write('22222222') # 光标移动到8后的同长度字符串替换
with open('1.txt', encoding='utf-8', mode='r+')as f:
f.write('22222222')
f.flush()