码迷,mamicode.com
首页 > 编程语言 > 详细

python 点滴记录8:文件操作read、readline与readlines

时间:2015-05-29 18:29:07      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:python   read   readline   readlines   

python读取文件内容时,有三种方法:read()、readline()和readlines()

这三种方法区别如下:

read(...)
    read([size]) -> read at most size bytes, returned as a string.
    
    If the size argument is negative or omitted, read until EOF is reached.
    Notice that when in non-blocking mode, less data than what was requested
    may be returned, even if no size parameter was given.

简单说,read()方法若不指定读取字节数,默认读取全部文件内容(所有文件内容存在内存),生成一个字符串。

  

readline(...)
      readline([size]) -> next line from the file, as a string.
    
      Retain newline.  A non-negative size argument limits the maximum
      number of bytes to return (an incomplete line may be returned then).
      Return an empty string at EOF.

简单说,readline()方法若不指定读取的字节数,默认每次读取一行,生成一个字符串。每执行一次readline()方法,则读取文件的一行。可用循环来完成整个文件的读取。


readlines(...)
    readlines([size]) -> list of strings, each a line from the file.
    
    Call readline() repeatedly and return a list of the lines so read.
    The optional size argument, if given, is an approximate bound on the
    total number of bytes in the lines returned.

简单说,readlines()方法若不指定读取的字节数,默认读取整个文件内容(所有文件内容存在内存),生成一个列表。列表中的每个元素是文件的一行。可用for循环打印没一行。


注:对于很大的文件,不适合使用read()和readlines()方法。因为这两种方法都是一次性将文件内容读取完放入内存。

python 点滴记录8:文件操作read、readline与readlines

标签:python   read   readline   readlines   

原文地址:http://ahaii.blog.51cto.com/1695127/1656419

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!