python 点滴记录8:文件操作rea
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()方法。因为这两种方法都是一次性将文件内容读取完放入内存。
相关文章