zoukankan      html  css  js  c++  java
  • python逐行读取

    From:https://blog.csdn.net/enweitech/article/details/78790888

    下面是四种Python逐行读取文件内容的方法, 并分析了各种方法的优缺点及应用场景,以下代码在python3中测试通过, python2中运行部分代码已注释,稍加修改即可。

    方法一:readline函数

    1
    2
    3
    4
    5
    6
    7
    8
    #-*- coding: UTF-8 -*- 
    = open("/pythontab/code.txt")             # 返回一个文件对象  
    line = f.readline()             # 调用文件的 readline()方法  
    while line:  
        #print line,                 # 在 Python 2中,后面跟 ',' 将忽略换行符  
        print(line, end = '')       # 在 Python 3中使用
        line = f.readline()
    f.close()

    优点:节省内存,不需要一次性把文件内容放入内存中

    缺点:速度相对较慢

    方法二:一次读取多行数据

    代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #-*- coding: UTF-8 -*- 
    = open("/pythontab/code.txt")
    while 1:
        lines = f.readlines(10000)
        if not lines:
            break
        for line in lines:
            print(line)
    f.close()

    一次性读取多行,可以提升读取速度,但内存使用稍大, 可根据情况调整一次读取的行数

    方法三:直接for循环

    在Python 2.2以后,我们可以直接对一个file对象使用for循环读每行数据

    代码如下:

    1
    2
    3
    4
    #-*- coding: UTF-8 -*- 
    for line in open("/pythontab/code.txt"):  
        #print line,  #python2 用法
        print(line)

    方法四:使用fileinput模块

    1
    2
    3
    4
    import fileinput
      
    for line in fileinput.input("/pythontab/code.txt"):
        print(line)

    使用简单, 但速度较慢  (file.open)

  • 相关阅读:
    SQL的update from 理解
    JS自动合并表格
    完全备份ORACLE数据库 并在另一台电脑上恢复
    cmd 连接到指定路径
    oracle 11g 64位安装sqldeveloper打开不了
    oracle 11g卸载方法
    sql的游标使用(转)
    JQEUERY案例
    sessionStorage实现note的功能
    Web Worker模拟抢票
  • 原文地址:https://www.cnblogs.com/seasondaily/p/9642118.html
Copyright © 2011-2022 走看看