zoukankan      html  css  js  c++  java
  • python 逐行读取文件的几种方法

    Python四种逐行读取文件内容的方法

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

    方法一:readline函数

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

    优点:节省内存,不需要一次性把文件内容放入内存中。
    缺点:速度相对较慢。

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

    代码如下:
    # -*- coding: UTF-8 -*-
    f = open("/pythontab/code.txt")
    while 1:
        lines = f.readlines(10000)
        if not lines:
            break
        for line in lines:
            print(line)
    f.close()
    

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

    方法三:直接for循环

    可以直接对一个file对象使用for循环读每行数据,代码如下:

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

    方法四:使用fileinput模块

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

    使用简单, 但速度较慢

    转载自:https://www.jianshu.com/p/4658e3ed1fea

  • 相关阅读:
    leetcode401 二进制手表问题
    HashMap与Hashtable
    ideal配置web项目
    java多线程
    spring boot项目启动报错:Failed to load property source from location 'classpath:/application.yml'
    spring cloud实例Dome详细搭建(一)
    ideal激活方法
    Go学习第三章面向对象
    Go学习第二章内建容器
    Go学习第一章基础语法
  • 原文地址:https://www.cnblogs.com/wlw-x/p/12305918.html
Copyright © 2011-2022 走看看