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

    一,文件操作基本流程。

    # 1.打开文件,产生文件句柄
    # 2.操作文件句柄
    # 3.关闭文件句柄
    # f1 = open('11.txt',encoding='utf-8', mode='r')
    # content = f1.read()
    # print(content)
    # f1.close()
    # f1, 文件句柄,文件对象
    # 约定俗称: file, f_handle ,file_handle, f_obj ,f1
    # open 打开的指令,windows的指令

    关闭文件的注意事项:

    打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
    1、f.close() #回收操作系统级打开的文件
    2、del f #回收应用程序级的变量
    
    其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
    而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()
    
    虽然我这么说,但是很多同学还是会很不要脸地忘记f.close(),对于这些不长脑子的同学,我们推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文
    with open('a.txt','w') as f:
        pass
     
    with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
        data=read_f.read()
        write_f.write(data)

    二,文件编码

    f=open(...)是由操作系统打开文件,那么如果我们没有为open指定编码,那么打开文件的默认编码很明显是操作系统说了算了
    # windows默认编码方式是gbk, linux默认编码方式是utf-8,mac:utf-8
    # f1 = open('11.txt', mode='rb')
    # content = f1.read()
    # print(content)
    # f1.close()
    # b 模式无需定义编码,主要用于非文字类的文件操作,比如图片,视频
    # r rb r+ r+b
    # w wb w+ w+b
    # a ab a+ a+b

    三,文件读的几种模式

    #1. read 全部读出来
    # f1 = open('11.txt', mode='r', encoding='utf-8')
    # print(f1.read())
    # f1.close()
    
    #1.1 read[n] 指定读取
    # f1 = open('11.txt', mode='r',encoding='utf-8')
    # print(f1.read(12))  #r模式是按照字符去读
    # f1.close()
    
    # f1 = open('11.txt', mode='rb')
    # print(f1.read(16))  #rb模式是按照字节去读
    # f1.close()
    
    #2. readline 按行读取
    '''
        def readline(self, limit=-1):
            """Read and return one line from the stream.
    
            :type limit: numbers.Integral
            :rtype: bytes
            """
            return b''
    '''
    # f1 = open('11.txt', mode='r',encoding='utf-8')
    # print(f1.readline())
    # print(f1.readline())
    # f1.close()
    
    #3. readlines
    '''
        def readlines(self, hint=-1):
            """Read and return a list of lines from the stream.
    
            :type hint: numbers.Integral
            :rtype: list[unicode]
            """
            return []
    '''
    
    #4. for循环 最后读取大文件的方式,只占一行的内存
    # f1  = open('11.txt', 'r', encoding='utf-8')
    # for n in f1:
    #     print(n)
    read(3):
    
      1. 文件打开方式为文本模式时,代表读取3个字符
    
      2. 文件打开方式为b模式时,代表读取3个字节
    
    其余的文件内光标移动都是以字节为单位的如:seek,tell,truncate
    
    注意:
    
      1. seek有三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的
    
      2. truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果。
    # seek() tell()
    # seek(0,2) 指针调到最后
    # tell() 告诉指针位置
    # f1 = open('11.txt', 'r', encoding='utf-8')
    # f1.seek(0,2)
    # print(f1.read())

    四、文件的修改

    文件的数据是存放于硬盘上的,因而只存在覆盖、不存在修改这么一说,

    方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的

    方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件

    #1. 打开文件产生文件句柄
    #2. 创建新文件产生文件句柄
    #3. 读取源文件,进行修改,写入新文件
    #4. 将源文件删除
    #5. 将文件命名源文件
    import os
    # low版
    # with open('11.txt', 'r', encoding='utf-8') as f1,
    #     open('11.bak', 'w', encoding='utf-8') as f2:
    #     old_content = f1.read()
    #     new_content = old_content.replace('我爱你', '我擦了')
    #     f2.write(new_content)
    # os.remove('11.txt')
    # os.rename('11.bak', '11.txt')
    
    #for循环版
    # with open('11.txt', 'r', encoding='utf-8') as f1,
    #     open('11.bak', 'w', encoding='utf-8') as f2:
    #     for line in f1:
    #         new_content = line.replace('我擦了', '我爱你')
    #         f2.write(new_content)
    # os.remove('11.txt')
    # os.rename('11.bak', '11.txt')

    五、练习

    1. 文件a.txt内容:每一行内容分别为商品名字,价钱,个数。

    apple 10 3

    tesla 100000 1

    mac 3000 2

    lenovo 30000 3

    chicken 10 3

    通过代码,将其构建成这种数据类型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱。

    # l1 = []
    # sum = 0
    # with open('a.txt', 'r', encoding='utf-8') as f1:
    #     for n in f1:
    #         n = n.split()
    #         if n:
    #             sum += int(n[1]) * int(n[2])
    #             l1.append({"name": n[0], "price": n[1], "amount": n[1]})
    # print(sum)
    # print(l1)

    2,有如下文件:

    -------

    alex是老男孩python发起人,创建人。

    alex其实是人妖。

    谁说alex是sb?

    你们真逗,alex再牛逼,也掩饰不住资深屌丝的气质。

    ----------

    将文件中所有的alex都替换成大写的SB。

  • 相关阅读:
    使用 Eclipse 调试 Java 程序的 10 个技巧
    oracle9i,10g再谈优化模式参数问题.
    oracle 索引
    解决IE不能在新窗口中向父窗口的下拉框添加项的问题
    获取文档的尺寸:利用Math.max的另一种方式
    揭开constructor属性的神秘面纱
    测试杂感:Windows8也许需要Account Hub
    探索式测试:探索是为了学习
    一次有教益的程序崩溃调试 (下)
    软件测试读书列表 (2013.8)
  • 原文地址:https://www.cnblogs.com/zh-lei/p/8874008.html
Copyright © 2011-2022 走看看