Python - 02 - 文件操作

196 阅读1分钟

文件读取

f = open('text.txt',mode='r',encoding='utf-8')
f是文件与程序之间的管道,由于文件可能过大,不能立即加载到内存中,所以只有在想要读取的时候调用read()来获取content
content = f.read()
  • readline() : 读取一行
  • readlines(): 一行一行的全部读取出来加到数组中,并且会将每一行末尾银行的换行符\n一起打印出来
  • 推荐读取:
    for line in f: 
     print(line.strip())
     //strip()是将每一行末尾\n去除
    
  • close:每次操作完都要进行关闭连接操作
  • write:写入,每次open的时候,mode="m"都会将文件内容清空
  • append:追加写入
  • with: 上下文,不用手动close
    • with open() as f:
  • open("path",mode="rb") b这个代表读取非文本文件 bytes

文件写入

  • 文件复制
    with open('filepath',mode="rb") as f1, \
        open('newfilepath',mode="wb") as f2: 
        for line in f1:
            f2.write(line)
    

文件修改

  • 修改内容
    1. 从源文件中读取内容
    2. 从内存中进行调整修改
    3. 把修改后的内容写入新文件
    4. 删除源文件
    5. 新文件重命名为源文件名字
       with open('filepath',mode="rb") as f1, \
      open('newfilepath',mode="wb") as f2: 
      for line in f1:
          line = line.strip()
          if line.startWith("1"):
              line = line.replace("1","2")
          f2.write(line)
          f2.write("\n")
          
      os.remove("filename")
      os.rename("newfilename","filename")
    
  • os:文件操作模块

tips

  • \ :代表 当前行和下一行是一行代码,因为python是解释型语言