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

    import time
    
    # with open('access.log', mode='rt',encoding="utf-8") as f:
    #     # 1、将指针跳到文件末尾
    #     # f.read() # 错误
    #     f.seek(0, 2)
    #
    #     while True:
    #         line = f.readline()  # 读一行
    #         if len(line) == 0:
    #             time.sleep(0.3)
    #         else:
    #             print(line, end='')
    
    
    with open('access.log', mode='rb') as f:
        # 1、将指针跳到文件末尾
        # f.read() # 错误
        f.seek(0, 2)
    
        while True:
            line = f.readline() + b'\n'  # 读一行
            if line == b'\n':
                time.sleep(0.3)
            else:
                print(line.decode('utf-8'), end='')

    文件修改的两种方式

    # 方式一:文本编辑采用的就是这种方式
    # 实现思路:将文件内容发一次性全部读入内存,然后在内存中修改完毕后再覆盖写回原文件
    # 优点: 在文件修改过程中同一份数据只有一份
    # 缺点: 会过多地占用内存
    # with open('c.txt',mode='rt',encoding='utf-8') as f:
    #     res=f.read()
    #     data=res.replace('alex','dsb')
    #     print(data)
    #
    # with open('c.txt',mode='wt',encoding='utf-8') as f1:
    #     f1.write(data)
    
    
    # 方式二:
    import os
    # 实现思路:以读的方式打开原文件,以写的方式打开一个临时文件,一行行读取原文件内容,修改完后写入临时文件...,删掉原文件,将临时文件重命名原文件名
    # 优点: 不会占用过多的内存
    # 缺点: 在文件修改过程中同一份数据存了两份
    with open('c.txt', mode='rt', encoding='utf-8') as f, \
            open('.c.txt.swap', mode='wt', encoding='utf-8') as f1:
        for line in f:
            f1.write(line.replace('alex', 'dsb'))
    
    os.remove('c.txt')
    os.rename('.c.txt.swap', 'c.txt')
    # 三、函数返回值
    # return是函数结束的标志,即函数体代码一旦运行到return会立刻
    # 终止函数的运行,并且会将 return 后的值当做本次运行的结果返回:
    # 1、返回None:函数体内没有return
    # return
    # return None
    #
    # 2、返回一个值:return 值
    # def func():
    # return 10
    #
    # res=func()
    # print(res)

  • 相关阅读:
    [LeetCode] Max Area of Island
    [TCP/IP] TCP数据报
    [LeetCode] Number of Islands
    [LeetCode] Binary Number with Alternating Bits
    [TCP/IP] Internet协议
    [LeetCode] Isomorphic Strings
    [LeetCode] Path Sum
    [LeetCode] Count and Say
    [学习OpenCV攻略][001][Ubuntu安装及配置]
    [国嵌攻略][038][时钟初始化]
  • 原文地址:https://www.cnblogs.com/pythonwork/p/15580429.html
Copyright © 2011-2022 走看看