read([size])方法:注意size是可选的
特点是:读取整个文件,将文件内容放到一个字符串变量中。
劣势是:如果文件非常大,尤其是大于内存时,无法使用read()方法。
read([size]):从文件中当前位置读取size个字节,若没有参数,则表示读取至结束为止,返回为字符串对象(整个读取的内容为一个字符串)
但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理
a.txt的内容如下所示:
Hello Welcome What is the fuck...
*
结果
Hello
Welcome
What is the fuck...
<type 'str'> #字符串类型
2***
readline()方法
特点:readline()方法每次读取一行;返回的是一个字符串对象,保持当前行的内存
缺点:比readlines慢得多
f = open("a.txt")
line = f.readline()
print(type(line))
while line:
print line,
line = f.readline()
f.close()
<type 'str'>
Hello
Welcome
What is the fuck...
3 ***
readlines()
readlines()方法读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素,但读取大文件会比较占内存。
f = open("a.txt")
lines = f.readlines()
print(type(lines))
for line in lines:
print line,
f.close()
<type 'list'>
Hello
Welcome
What is the fuck...
4 ***
linecache模块
# 输出第2行
text = linecache.getline(‘a.txt',2)
print text,