• day9.关于文件的操作


    一、文件操作

    """
    fp = open("文件名",mode="模式",encoding="utf-8")
    fp -> 文件的io对象 (文件句柄)
    i => input  输入
    o => output 输出
    """

    1、文件的写入

    # 1.打开文件
    fp = open("ceshi1.txt",mode="w",encoding="utf-8") # 把冰箱门打开
    
    # 2.写入内容
    fp.write("把大象塞进去") # 把大象放进去
    
    # 3.关闭文件
    fp.close() # 把冰箱门关上
    文件的写入

    2、文件的读取

    # 1.打开文件
    fp = open("ceshi1.txt",mode="r",encoding="utf-8") #1.打开冰箱门
    
    # 2.读取内容
    res = fp.read() # 把大象拿出来
    print(res)
    
    # 3.关闭文件
    fp.close() # 把冰箱门关上
    文件的读取

    3、字节流的转换

    """
    bytes : 是用来传输或者存储的数据格式
    b'1234'  b"abcd" b"我爱你" -> b开头的字节流,范围只能是ascii编码
    
    如果是中文使用encode 和 decode 来进行转换;
    # 将字符串和字节流(Bytes流)类型进行转换 (参数写成转化的字符编码格式)
        #encode() 编码  将字符串转化为字节流(Bytes流)
        #decode() 解码  将Bytes流转化为字符串
    """
    a = b'1234'
    print(a , type(a))

    编码与解码

    strvar = "我爱你"
    # encode 编码 -> 变成二进制字节流
    res = strvar.encode("utf-8")
    print(res , type(res))
    
    # decode 解码 =>二进制字节流恢复成原来的字符串
    res2 = res.decode("utf-8")
    print(res2 , type(res2))
    
    # len可以计算字节个数
    num = len(res)
    print(num) # 9
    
    # 一个中文占用3个字节,通过decode 反解出爱这个字
    res3 = b"xe7x88xb1".decode("utf-8")
    print(res3)
    
    #  程序员的表白方式
    strvar = "我!是你一辈子也得不到的男人"
    strvar2 = strvar.encode()
    print(strvar2)
    View Code

    4、存储二进制字节流

    不需要指定encoding编码集,否则报错

    fp = open("ceshi2.txt",mode="wb")
    fp.write(strvar2)
    fp.close()

    5、读取二进制字节流

    fp = open("ceshi2.txt",mode="rb")
    res = fp.read()
    fp.close()
    
    print(res)
    # 通过decode反解出字符串
    strvar = res.decode()
    print(strvar)

    6、复制图片

    """图片,音频,视频"""
    # 1.读取原图片所有的内容
    fp = open("集合.png",mode="rb")
    res = fp.read()
    fp.close() 
    
    # 2.把读取的内容存储到另外一个文件
    # fp = open("集合2.png",mode="wb")
    # 指定绝对路径(完整路径)
    fp = open(r"E:python31day8集合3.png",mode="wb")
    fp.write(res)
    fp.close()

    二、文件的扩展模式

    # ### 文件的扩展模式
    # (utf-8编码格式下 默认一个中文三个字节 一个英文或符号 占用一个字节)
        #read()        功能: 读取字符的个数(里面的参数代表字符个数)
        #seek()        功能: 调整指针的位置(里面的参数代表字节个数)
        #tell()        功能: 当前光标左侧所有的字节数(返回字节数)
    """
    seek(0)   直接把光标移动到文件开头
    seek(0,2) 直接把光标移动到文件末尾
    第二个参数 0:开头 1:当前位置 2:文件末尾
    """

    1、文件的扩展模式

    r+ 先读后写

    """
    fp = open("ceshi3.txt",mode="r+",encoding="utf-8") 
    # 先读
    res = fp.read()
    print(res)
    
    # 后写
    fp.write("1234")
    
    # 在读
    fp.seek(0) # 调整光标位置在开头
    res = fp.read()
    print(res)
    fp.close()
    """

    r+ 先写后读

    """
    fp = open("ceshi3.txt",mode="r+",encoding="utf-8")
    fp.seek(0,2) # 调整光标位置在末尾
    fp.write("123")
    
    fp.seek(0)
    res = fp.read()
    print(res)
    fp.close()
    """

    w+ 可读可写

    """
    fp = open("ceshi4.txt",mode="w+",encoding="utf-8")
    fp.write("abc")
    
    fp.seek(0)
    res = fp.read()
    print(res)
    fp.close()
    """

    a+ 可读可写

    """文件不存在时,默认创建新的文件"""
    """
    fp = open("ceshi5.txt",mode="a+",encoding="utf-8")
    fp.write("123")
    
    fp.seek(0)
    res = fp.read()
    print(res)
    
    # a模式在写入内容时,会强制把光标移动到最后
    fp.seek(1)
    fp.write("abc")
    
    fp.close()
    
    
    # 如果在r模式内,区别a模式
    fp = open("ceshi5.txt",mode="r+",encoding="utf-8")
    fp.seek(1)
    fp.write("abc")
    fp.close()
    """

    2、read  seek tell 三个函数的使用

    """
    fp = open("ceshi6.txt",mode="r+",encoding="utf-8")
    res = fp.read(3)
    print(res)
    
    fp.seek(6)
    print(fp.read(1))
    
    # 计算文件指针左侧所有的字节数
    res = fp.tell()
    print(res)
    fp.close()
    """

    注意点

    # 注意点,seek移动中文字节的时候,有可能报错
    """
    fp = open("ceshi6.txt",mode="r+",encoding="utf-8")
    fp.seek(2)
    res = fp.read()
    print(res)
    fp.close()
    
    # print("我".encode())
    # b'xe6x88x91'
    """
    
    # 三.with语法的使用 (close操作with语法可以自动实现)
    with open("集合.png",mode="rb") as fp:
        res = fp.read()
    
    with open(r"E:python31day8集合4.png",mode="wb") as fp:
        fp.write(res)
    
    # 继续优化 合并with
    with open("集合.png",mode="rb") as fp1 ,  open(r"E:python31day8集合5.png",mode="wb") as fp2:
        res = fp1.read()
        fp2.write(res)
    View Code

    三、文件的相关函数

    """
    # 刷新缓冲区 flush
        # 当文件关闭的时候自动刷新缓冲区
        # 当整个程序运行结束的时候自动刷新缓冲区
        # 当缓冲区写满了  会自动刷新缓冲区
        # 手动刷新缓冲区
    fp = open("ceshi6.txt",mode="r+",encoding="utf-8")
    fp.write("zzz")
    # 手动把缓冲区里面的内容写入文件当中
    fp.flush()
    
    while True:
        pass
    
    fp.close()
    """

    链接:关于flush刷新

    flush刷新https://blog.csdn.net/pjliyuhang/article/details/91831734

    1、文件相关的函数

    fp = open("ceshi6.txt",mode="a+",encoding="utf-8")
    #readable()        功能: 判断文件对象是否可读
    res = fp.readable()
    print(res)
    #writable()        功能: 判断文件对象是否可写
    res = fp.writable()
    print(res)
    #readline()     功能: 读取一行文件内容
    
    """
    参数 > 当前行字符总个数 => 以当前行读取
    参数 < 当前行字符总个数 => 以参数的大小来读取字符的个数
    
    默认readline 读取一行
    """
    
    """
    with open("ceshi7.txt",mode="r+",encoding="utf-8") as fp:    
        # res = fp.readline(3000)
        # print(res)
        
        # 文件对象fp也是一个可迭代对象
        '''在遍历文件对象的时候,默认一次拿一行'''
        for i in fp:
            print(i)
    
    # 读取所有内容
    with open("ceshi7.txt",mode="r+",encoding="utf-8") as fp:    
    
        # 先读取一行
        res = fp.readline()
        # 判断是不是空
        while res:
            print(res)
            res = fp.readline()
    
    """

    1.1、readlines()

    功能:将文件中的内容按照换行读取到列表当中

    lst_new = []
    with open("ceshi7.txt",mode="r+",encoding="utf-8") as fp:    
        lst = fp.readlines()
        # print(lst) # ['	窗前明月光
    ', '疑是鞋两双		
    ', '		举头王明月
    ', '	低头看裤裆']
        for i in lst:        
            lst_new.append(i.strip())
    
    print(lst_new)     # ['窗前明月光', '疑是鞋两双', '举头王明月', '低头看裤裆']

    1.2、writelines()

    功能:将内容是字符串的可迭代性数据写入文件中 参数:内容为字符串类型的可迭代数据

    """可迭代型数据(容器类型数据,range对象,迭代器)"""
    """
    lst = ["春眠不觉晓
    ","处处蚊子咬
    ","夜来大狗熊
    ","一个也跑不了
    "]
    # lst = [1,2,3,4] error
    with open("ceshi8.txt",mode="w",encoding="utf-8") as fp:
        fp.writelines(lst)
    """

    1.3、truncate()

    功能: 把要截取的字符串提取出来,然后清空内容将提取的字符串重新写入文件中 (字节)

    with open("ceshi8.txt",mode="r+",encoding="utf-8") as fp:
        fp.truncate(3)

     四、练习

    '''
    #1.有如下文件,a1.txt,里面的内容为:
        键盘敲烂,
        月薪过万.
        键盘落灰,
        狗屎一堆.
    
    分别完成以下的功能:
    a:将原文件全部读出来并打印。
    b:在原文件后面追加一行内容:信不信由你,反正我信了。
    c:将原文件全部读出来,并在后面添加一行内容:信不信由你,反正我信了。
    d:将原文件全部清空,换成下面的内容:
        每天坚持一点,
        每天努力一点,
        每天多思考一点,
        慢慢你会发现,
        你的进步越来越大。
    
    e:将原文件内容全部读取出来,
        并在'键盘落灰'这一行的前面加一行,'年薪百万'
        然后将更改之后的新内容,写入到一个新文件:a1.txt。
        
    #2.有如下文件,t1.txt,里面的内容为:
        葫芦娃,葫芦娃,
        一根藤上七个瓜
        风吹雨打,都不怕,
        啦啦啦啦。
        上面的内容你肯定是心里默唱出来的,对不对
        
    分别完成下面的功能:
    a:以r+的模式打开原文件,判断原文件是否可读,是否可写。
    b:以r的模式打开原文件,利用for循环遍历文件对象。
    c:以r的模式打开原文件,以readlines()方法读取出来,并循环遍历        
    d:以r模式读取‘葫芦娃,’前四个字符。
    e:以r模式读取第一行内容,并去除此行前后的空格,制表符,换行符。
    f:以r模式打开文件,从‘风吹雨打.....’开始读取,一直读到最后。
    g:以a+模式打开文件,先追加一行:‘老男孩教育’然后在全部读取出来。
    h:截取原文件,截取内容:‘葫芦娃,葫芦娃,’
        
        
        
    #3.文件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}
    ] 
    '''
    with open("a1.txt",mode="r+",encoding="utf-8") as fp:
        res = fp.read()
        print(res)
    1-a
    with open("a1.txt",mode="a+",encoding="utf-8") as fp:
        fp.write("
    	信不信由你,反正我信了")
    1-b
    with open("a1.txt",mode="a+",encoding="utf-8") as fp:
        fp.seek(0)
        res = fp.read()
        fp.write("
    	信不信由你,反正我信了")
    1-c
    strvar = '''
        每天坚持一点,
        每天努力一点,
        每天多思考一点,
        慢慢你会发现,
        你的进步越来越大。
    '''
    with open("a1.txt",mode="w+",encoding="utf-8") as fp:
        fp.write(strvar)
    1-d
    with open("a1.txt",mode="r+",encoding="utf-8") as fp1,open("a2.txt",mode="w+",encoding="utf-8") as fp2:
        lst = fp1.readlines()
        print(lst)
        lst.insert(2,"	年薪百万,
    ")
        fp2.writelines(lst)
    1-e
    fp = open("t1.txt",mode="r+",encoding="utf-8")
    print(fp.readable())
    print(fp.writable())
    2-a
    with open("t1.txt",mode="r",encoding="utf-8") as fp:
        for i in fp:
            print(i.strip())
    2-b
    with open("t1.txt",mode="r",encoding="utf-8") as fp:
        lst = fp.readlines()
        for i in lst:
            print(i)
    2-c
    在r模式下,read读取的是字符
    在rb模式下,read组曲的是字节
    
    with open("t1.txt",mode="r",encoding="utf-8") as fp:
        res = fp.read(4) # 字符个数
        print(res)
            
    with open("ceshi.txt",mode="rb") as fp:
        res = fp.read(3)
        print(res.decode())
    2-d
    with open("t1.txt",mode="r",encoding="utf-8") as fp:
        res = fp.readline()
        print(res.strip())
    2-e
    with open("t1.txt",mode="r",encoding="utf-8") as fp:
        lst = fp.readlines()
        # print(lst)
        # print(lst[2:])
        for i in lst[2:]:
            print(i)
    2-f
    with open("t1.txt",mode="a+",encoding="utf-8") as fp:
        fp.write("
    	老男孩教育")
        fp.seek(0)
        print(fp.read())
    2-g
    with open("t1.txt",mode="r+",encoding="utf-8") as fp:
        fp.truncate(24)
    2-h
    lst_new = []
    total = 0
    with open("a.txt",mode="r+",encoding="utf-8") as fp:
        lst = fp.readlines()
        print(lst)
        for i in lst:
            dic = {}
            name,price,amount = i.strip().split()
            dic["name"] = name
            dic["price"] = float(price)
            dic["amount"] = float(amount)
            lst_new.append(dic)
            total += dic["price"] * dic["amount"] 
        print(lst_new)
        print(total)
    3
  • 相关阅读:
    JavaScript--Promise(1)
    JavaScript--创建对象
    JavaScript--JSON
    JavaScript--generator
    JavaScript--闭包(1)
    JavaScript--sort()
    JavaScript--filter()
    JavaScript--map()&reduce()
    JavaScript--map&set
    3.11
  • 原文地址:https://www.cnblogs.com/kongxiangqun/p/13308653.html
Copyright © 2020-2023  润新知