读相关操作

readline

  1. # 1、readline:一次读一行
  2. with open(r'g.txt', mode='rt', encoding='utf-8') as f:
  3. while True:
  4. line = f.readline()
  5. if len(line) == 0:
  6. break
  7. print(line)

readlines

  1. with open(r'g.txt', mode='rt', encoding='utf-8') as f:
  2. res = f.readlines() # 生成一个列表
  3. print(res)

执行流程.gif

写相关操作

writelines

  1. with open('h.txt', mode='wt', encoding='utf-8') as f:
  2. # f.write('1111\n222\n3333\n')
  3. # l=['11111\n','2222','3333',4444]
  4. l = ['11111\n', '2222', '3333']
  5. # for line in l:
  6. # f.write(line)
  7. f.writelines(l)
  1. with open('h.txt', mode='wb') as f:
  2. # l = [
  3. # '1111aaa1\n'.encode('utf-8'),
  4. # '222bb2'.encode('utf-8'),
  5. # '33eee33'.encode('utf-8')
  6. # ]
  7. # 补充1:如果是纯英文字符,可以直接加前缀b得到bytes类型
  8. # l = [
  9. # b'1111aaa1\n',
  10. # b'222bb2',
  11. # b'33eee33'
  12. # ]
  13. # 补充2:'上'.encode('utf-8') 等同于bytes('上',encoding='utf-8')
  14. l = [
  15. bytes('上啊', encoding='utf-8'),
  16. bytes('冲呀', encoding='utf-8'),
  17. bytes('小垃圾们', encoding='utf-8'),
  18. ]
  19. f.writelines(l)

flush

flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。
一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。
一般用于测试

  1. with open('h.txt', mode='wt',encoding='utf-8') as f:
  2. f.write('哈')
  3. f.flush()
  1. # 4、了解
  2. with open('h.txt', mode='wt', encoding='utf-8') as f:
  3. print(f.readable()) # False
  4. print(f.writable()) # True
  5. print(f.encoding) # utf-8
  6. print(f.name) # h.txt
  7. print(f.closed) # True