zoukankan      html  css  js  c++  java
  • python基础-read、readline、readlines的区别

    一、read([size])方法
    read([size])方法从文件当前位置起读取size个字节,若无参数size,则表示读取至文件结束为止,它范围为字符串对象:
     
    f = open("read.txt")
    lines = f.read()
    print(lines.rstrip())
    print(type(lines))
    f.close()
    输出结果:
    Hello
    Welcome
    What is the fuck...
    <class 'str'>
     
    二、readline()方法
    从字面意思可以看出,该方法每次读出一行内容,所以,读取时占用内存小,比较适合大文件,该方法返回一个字符串对象:
    f = open("read.txt")
    line = f.readline()
    print(type(line))
    while line:
    print(line.rstrip())
    line = f.readline()
    f.close()
    输出结果:
    <class 'str'>
    Hello
    Welcome
    What is the fuck...
     
    三、readlines()方法 
    读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素,但读取大文件会比较占内存:
    f = open("read.txt")
    lines = f.readlines()
    print(type(lines))
    for line in lines:
    print(line.rstrip())
    f.close()
    输出结果:
    <class 'list'>
    Hello
    Welcome
    What is the fuck...
     
    'decode' >>>

  • 相关阅读:
    C# 反射
    jquery 循环绑定click的问题
    socket 编程
    EF code first出现错误:列名 Discriminator 无效
    C# 两个类是否继承关系
    C# MD5,hmacSHA1
    文件分块上传
    读写CSV到DataTable
    ajax 提交数组 泛型集合(嵌套集合)
    Json中Date映射到model
  • 原文地址:https://www.cnblogs.com/Suomy/p/10028121.html
Copyright © 2011-2022 走看看