zoukankan      html  css  js  c++  java
  • 关于python文件写入问题

    第一种、用for循环不断打开文件写入关闭 测试代码数据如下:
    import time
    
    
    begin = time.perf_counter()
    
    
    def a(f, lis):
        f.write(lis + '
    ')
    
    
    lis = 'hello'
    lis2 = 'hello2'
    for i in range(100):
        with open('ces.txt', 'a+')as f:  # 写入文件
            a(f, lis)
            for j in range(10):
                with open('ces.txt', 'a+')as b:  # 写入文件
                    a(b, lis2)
           b.close()
      f.close()
    end = time.perf_counter()
    print('处理时长:' + '%.2f' % (end - begin) + '')
    
    # 处理时长:7.27秒

    第二种、下面是打开文件再for循环关闭的测试

    import time
    
    
    begin = time.perf_counter()
    
    
    def a(f, lis):
        f.write(lis + '
    ')
    
    
    lis = 'hello'
    lis2 = 'hello2'
    with open('ces.txt', 'a+')as f:  # 写入文件
        for i in range(100):
            a(f, lis)
            with open('ces.txt', 'a+')as b:  # 写入文件
                for j in range(10):
                    a(b, lis2)
                b.close()
        f.close()
    end = time.perf_counter()
    print('处理时长:' + '%.2f' % (end - begin) + '')
    
    # 处理时长:0.73秒

     总结如下:

      1.两者所花的时间差约10倍之长,推荐使用第二种

      2.文件内容写入顺序是从下到上

  • 相关阅读:
    junit spring
    DFU协议介绍
    USB枚举过程
    触摸板单点描述符
    Linux下使用codeblocks交叉编译ARM-LINUX-GCC程序
    树莓派 原理图 摄像头接口定义
    usb描述符详细讲解
    常用的算法思想
    STM32f407 DCMI方式驱动 OV2640
    linux echo命令-转
  • 原文地址:https://www.cnblogs.com/1314h/p/13228521.html
Copyright © 2011-2022 走看看