zoukankan      html  css  js  c++  java
  • Python中read()、readline()、readlines()的区别

    一、read()方法

    read([size])方法从文件当前位置起读取size个字节,若无参数size,则表示读取至文件结束为止,返回字符串对象

    fr = open("test.txt","r",encodin="utf-8")
    text = fr.read()
    print(text)
    print(type(text))
    fr.close()

    输出结果

    hello
    world
    zzzzzzzzzzwt
    <class 'str'>

    二、readline()方法

    readline()每次读出一行内容,所以,读取时占用内存小,比较适合大文件,返回字符串对象,每次读取时遇到换行符 就停止,下一次从下一行继续读取

    fr = open("/home/zwt/PycharmProjects/test/test.txt","r",encoding="utf-8")
    text1 = fr.readline()
    print(type(text1))
    print(text1)
    text2 = fr.readline()
    print(text2)
    text3 = fr.readline()
    print(text3)
    fr.close()

    输出结果

    <class 'str'>
    hello
    world
    zzzzzzzzzzwt

    三、readlines()方法

    readlines()方法读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素,读取大文件会比较占内存

    fr = open("test.txt","r",encoding="utf-8")
    text = fr.readlines()
    print(text)
    print(type(text))
    fr.close()

    输出结果

    ['hello
    ', 'world
    ', 'zzzzzzzzzzwt
    ']
    <class 'list'>

    四、拓展linecache模块

    有特殊需求还可以用linecache模块,比如你要输出某个文件的第n行:

    text = linecache.getline("test.txt",2)
    print(text)

    输出结果

    world

    附件(密码hvqq):

    https://pan.baidu.com/s/1AVj0LysEmzFDZ7QB664fCA

  • 相关阅读:
    MarkDown测试
    在Tabbed Activity(ViewPager)中切换Fragment
    About ListView
    Android Studio的技巧
    卷积神经网络
    TensorFlow中CNN的两种padding方式“SAME”和“VALID”
    tensorflow-解决3个问题
    激活函数
    tensorflow数学运算
    tensorflow
  • 原文地址:https://www.cnblogs.com/zwtgyh/p/10627857.html
Copyright © 2011-2022 走看看