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 ']

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

  • 相关阅读:
    jquery web 國際化
    Struts2 分割字符串标签s:generator
    (55) 销售锁货功能
    (54) 记录销售单修改详细
    (53) 动态列表自定义
    exe文件作为服务启动
    (52)KeyError错误
    (51) magento集成增加到款通知
    (50)与magento集成
    (49) odoo context操作
  • 原文地址:https://www.cnblogs.com/cl1024cl/p/6205608.html
Copyright © 2011-2022 走看看