发布时间:2019-08-27 07:59:46编辑:auto阅读(1882)
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笔记(二)文本的创建和读取
下一篇: Python中类的属性、方法及内置方法
48863
47925
38705
35857
30283
27035
26068
20901
20697
19063
498°
593°
603°
605°
584°
570°
633°
708°
827°
926°