zoukankan      html  css  js  c++  java
  • python的read() 、readline()、readlines()、xreadlines()

    先来一个小例子:

    import sys

    dir= os.path.dirname(os.path.abspath(__file__))
    file_path='%s/test.txt'  % dir
    f= open(file_path,'r')

    #print f.read()
    print "----------------"
    for line in f.readlines():
        line.strip()
        print line
    #f.write('testxxx3xx33333333333')
    #print filet.read()
    f.close()

    输出结果为:

    ----------------
    fucttttx3tttt22221111133

    fucttttx3tttt22221111133

    fucttttx3tttt22221111133

      

    其实,python文件读入函数有read(), readline(), readlines() & xreadlines() func in Python

     介绍如下:

    * read(size) >> size is an optional numeric argument and this func returns a quantity of data equal to size. If size if omitted, then it reads the entire file and returns it

    读入指定大小的内容,以byte为单位,size为读入的字符数,返回str类型

    注意省略时,read()会读取整个文件,将读取到底的文件内容放到一个字符串变量,返回str类型

    * readline() >> reads a single line from file with newline at the end。

       readline()读取一行内容,放到一个字符串变量,返回str类型。

    * readlines() >> returns a list containing all the lines in the file

    readlines() 读取文件所有内容,按行为单位放到一个列表中,返回list类型。

    * xreadlines() >> Returns a generator to loop over every single line in the file

      返回一个生成器,来循环操作文件的每一行。循环使用时和readlines基本一样,但是直接打印就不同

    print f.xreadlines()
    print f.readlines()

    输出如下:

    <open file '/home/deve_test_user/liu/test.txt', mode 'r' at 0x2b1e19035cd8>

    ['f3tttt22221111133 ', 'fucttttx3tttt22221111133 ', 'fucttttx3tttt22221111133 ', 'fucttttx3tttt22221111133 ', 'fucttttx3tttt22221111133 ', 'fucttttx3tttt22221111133 ', 'fucttttx3tttt22221111133 ', 'fttx3tttt2222111113endend ']

    所以二者类型不同。但使用时相同。

  • 相关阅读:
    分形之城
    【SDOI2011 第2轮 DAY1】消防 树上问题+二分+贪心
    【Usaco Nov08 Gold】玩具 三分+贪心
    分治 复习
    快读板子
    最小线段覆盖 C神奇项链
    比赛经验积累1
    字符串 专题
    界面小项目之W3C
    前端小基础
  • 原文地址:https://www.cnblogs.com/cl1024cl/p/6205608.html
Copyright © 2011-2022 走看看