源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python读取文件内容的三种常用方式及效率比较

  • 时间:2021-02-08 02:22 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python读取文件内容的三种常用方式及效率比较
本文实例讲述了Python读取文件内容的三种常用方式。分享给大家供大家参考,具体如下: 本次实验的文件是一个60M的文件,共计392660行内容。 [img]http://img.1sucai.cn/uploads/article/2018010709/20180107090132_0_41819.jpg[/img] [b]程序一:[/b]
def one():
  start = time.clock()
  fo = open(file,'r')
  fc = fo.readlines()
  num = 0
  for l in fc:
    tup = l.rstrip('n').rstrip().split('t')
    num = num+1
  fo.close()
  end = time.clock()
  print end-start
  print num

运行结果:0.812143868027s [b]程序二:[/b]
def two():
  start = time.clock()
  num = 0
  with open(file, 'r') as f:
    for l in f:
      tup = l.rstrip('n').rstrip().split('t')
      num = num+1
  end = time.clock()
  times = (end-start)
  print times
  print num

运行时间:0.74222778078 [b]程序三:[/b]
def three():
  start = time.clock()
  fo = open(file,'r')
  l = fo.readline()
  num = 0
  while l:
    tup = l.rstrip('n').rstrip().split('t')
    l = fo.readline()
    num = num+1
  end = time.clock()
  print end-start
  print num

运行时间:1.02316120797 由结果可得出,程序二的速度最快。 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/672.htm]Python文本文件操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/809.htm]Python URL操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/645.htm]Python图片操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》及《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部