zoukankan      html  css  js  c++  java
  • 第四章文件操作

    第四章 文件操作

    4.1 文件基本操作

    obj = open('路径',mode='模式',encoding='编码')
    obj.write()
    obj.read()
    obj.close() 
    
    with open...
    

    4.2 打开模式

    • r / w / a
    • r+ / w+ / a+
    • rb / wb / ab
    • r+b / w+b / a+b

    4.3 操作

    • read() , 全部读到内存

    • read(1)

      • 1表示一个字符

        obj = open('a.txt',mode='r',encoding='utf-8')
        data = obj.read(1) # 1个字符
        obj.close()
        print(data)
        
      • 1表示一个字节

        obj = open('a.txt',mode='rb')
        data = obj.read(3) # 1个字节
        obj.close()
        
    • write(字符串)

      obj = open('a.txt',mode='w',encoding='utf-8')
      obj.write('中午你')
      obj.close()
      
    • write(二进制)

      obj = open('a.txt',mode='wb')
      
      # obj.write('中午你'.encode('utf-8'))
      v = '中午你'.encode('utf-8')
      obj.write(v)
      
      obj.close()
      
    • seek(光标字节位置),无论模式是否带b,都是按照字节进行处理。

      obj = open('a.txt',mode='r',encoding='utf-8')
      obj.seek(3) # 跳转到指定字节位置
      data = obj.read()
      obj.close()
      
      print(data)
      
      
      
      
      obj = open('a.txt',mode='rb')
      obj.seek(3) # 跳转到指定字节位置
      data = obj.read()
      obj.close()
      
      print(data)
      
    • tell(), 获取光标当前所在的字节位置

      obj = open('a.txt',mode='rb')
      # obj.seek(3) # 跳转到指定字节位置
      obj.read()
      data = obj.tell()
      print(data)
      obj.close()
      
    • flush,强制将内存中的数据写入到硬盘

      v = open('a.txt',mode='a',encoding='utf-8')
      while True:
          val = input('请输入:')
          v.write(val)
          v.flush()
      
      v.close()
      

    4.4 关闭文件

    文艺青年

    v = open('a.txt',mode='a',encoding='utf-8')
    
    v.close()
    
    

    二逼

    with open('a.txt',mode='a',encoding='utf-8') as v:
        data = v.read()
    	# 缩进中的代码执行完毕后,自动关闭文件
    
    

    4.5 文件内容的修改

    with open('a.txt',mode='r',encoding='utf-8') as f1:
        data = f1.read()
    new_data = data.replace('飞洒','666')
    
    with open('a.txt',mode='w',encoding='utf-8') as f1:
        data = f1.write(new_data)
    
    

    大文件修改

    f1 = open('a.txt',mode='r',encoding='utf-8')
    f2 = open('b.txt',mode='w',encoding='utf-8')
    
    for line in f1:
        new_line = line.replace('阿斯','死啊')
        f2.write(new_line)
    f1.close()
    f2.close()
    
    
    with open('a.txt',mode='r',encoding='utf-8') as f1, open('c.txt',mode='w',encoding='utf-8') as f2:
        for line in f1:
            new_line = line.replace('阿斯', '死啊')
            f2.write(new_line)
    
    
  • 相关阅读:
    [OpenGL ES 071]光照原理
    [OpenGL ES 03]3D变换:模型,视图,投影与Viewport
    [日志]当今最流行的网络生僻字,很火
    [日志]关于茶的基础知识
    [健康]快速除牙痛的八个小验方
    [日志]我们生活中的潜规则
    [日志]做事要方,做人要圆
    [日志]家居装修花钱看你怎么省
    [日志]非常宝贵的工作经验
    [日志]你用的着的一些家装尺寸数据
  • 原文地址:https://www.cnblogs.com/hanfe1/p/11511112.html
Copyright © 2011-2022 走看看