读相关操作
readline
# 1、readline:一次读一行
with open(r'g.txt', mode='rt', encoding='utf-8') as f:
while True:
line = f.readline()
if len(line) == 0:
break
print(line)
readlines
with open(r'g.txt', mode='rt', encoding='utf-8') as f:
res = f.readlines() # 生成一个列表
print(res)
写相关操作
writelines
with open('h.txt', mode='wt', encoding='utf-8') as f:
# f.write('1111\n222\n3333\n')
# l=['11111\n','2222','3333',4444]
l = ['11111\n', '2222', '3333']
# for line in l:
# f.write(line)
f.writelines(l)
with open('h.txt', mode='wb') as f:
# l = [
# '1111aaa1\n'.encode('utf-8'),
# '222bb2'.encode('utf-8'),
# '33eee33'.encode('utf-8')
# ]
# 补充1:如果是纯英文字符,可以直接加前缀b得到bytes类型
# l = [
# b'1111aaa1\n',
# b'222bb2',
# b'33eee33'
# ]
# 补充2:'上'.encode('utf-8') 等同于bytes('上',encoding='utf-8')
l = [
bytes('上啊', encoding='utf-8'),
bytes('冲呀', encoding='utf-8'),
bytes('小垃圾们', encoding='utf-8'),
]
f.writelines(l)
flush
flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。
一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。
一般用于测试
with open('h.txt', mode='wt',encoding='utf-8') as f:
f.write('哈')
f.flush()
# 4、了解
with open('h.txt', mode='wt', encoding='utf-8') as f:
print(f.readable()) # False
print(f.writable()) # True
print(f.encoding) # utf-8
print(f.name) # h.txt
print(f.closed) # True