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.文件内容写入顺序是从下到上

  • 相关阅读:
    笔记。------数组
    图片与文字的对齐方式
    clear:both;和overflow:hidden;的应用理解。
    淘宝首页
    错误:编码GBK的不可映射字符
    Java基础之反射
    (一)Servlet简介
    Windows10快捷键
    (二)Maven的安装与环境配置
    (一)Maven简介
  • 原文地址:https://www.cnblogs.com/1314h/p/13228521.html
Copyright © 2011-2022 走看看