读写文件的几种方式

手动方式

  • open+close
  • 三种模式
    w, write, 写
    r,read,读
    a, append,追加内容
  1. import os
  2. os.chdir(r'path') 切换到操作路径
  3. f = open('de8ug.txt', 'w')
  4. w方式打开文件,不存在则创建
  5. f.write('de8ug' * 8) # 写入字符串
  6. f.close()

自动方式

  • 相关模块

    • fnmatch
    • glob
    • pickle
    • StringIO
    • shelve
  • with open

  1. with open('de8ug-1.txt', 'w') as f:
  2. f.write('de8ug')
  3. with open('de8ug.txt') as f:
  4. data = f.read()
  5. print(data)
  6. with open('de8ug.txt') as f:
  7. print(f.readline()) *读取一行*
  8. with open('de8ug.txt', 'a') as f:
  9. 'a' 多几行,追加到源文件
  10. f.write('111111\n')
  11. f.write('111111\n')
  12. f.write('\n111111')
  13. f.write('\n111111')
  14. with open('de8ug.txt') as f:
  15. print(f.readlines()) #读取多行
  16. #结果返回一个列表
  17. ['de8ugde8ugde8ugde8ugde8ugde8ugde8ugde8ug111111\n', '111111\n', '\n', '111111\n', '111111']
  • fnmatch
    • 匹配相应后缀名的文件
  1. import fnmatch
  2. for f in os.listdir('test'):
  3. if fnmatch.fnmatch(f, '*.txt'):
  4. print(f)
  5. elif fnmatch.fnmatch(f, '\*.pdf'):
  6. print('find pdf', f)
  • *号匹配多个,若匹配单字符可用?号
  • *正则,?匹配一个字符
    • glob
  • 单纯匹配某种命名规则文件
  1. import glob
  2. for f in glob.glob('test/[0-9].doc'):
  3. print(f)
  4. test\0.doc
  5. test\1.doc
  6. test\2.doc
  7. test\3.doc
  8. test\4.doc
  • pickle
    • 序列化存储
  1. # 序列化 pickle,持久化,存盘
  2. # 后缀名随意,推荐pkl
  3. # 存储Python的数据结构
  4. name_list = ['de8ug', 'lilei', 'hmm']
  5. data = {'name': name_list, 'age': (4,5,6)}
  6. import pickle
  7. with open('data.pkl', 'wb') as f:
  8. # 使用‘wb’,通用二进制存储
  9. pickle.dump(data, f)
  10. with open('data.pkl', 'rb') as f:
  11. # 'rb', 读写都二进制
  12. data = pickle.load(f)
  13. print(data)
  14. {'name': ['de8ug', 'lilei', 'hmm'], 'age': (4, 5, 6)}
  • io
    • 虚拟化读写
  1. # 虚拟文件,临时文件,不需要真的保存文件到磁盘
  2. import io
  3. output = io.StringIO()
  4. output.write('第2行代码\n')
  5. print('试一下print到文件:', file=output)
  6. # 取出内容
  7. contents = output.getvalue()
  8. print(contents)
  9. # 关闭文件,清理缓存
  10. output.close()


  • shelve
    • 用类似字典的方式存储任意的Python对象
import shelve
with shelve.open('de8ug.she') as so:
  so['de8ug'] = '存一下888888这个值'
with shelve.open('de8ug.she') as so:
  print(so['de8ug'])
存一下888888这个值