python read() readline() readlines() write() writelines()方法总结与区别输出: read()方法用于直接读取字节到字符串中,可以接参数给定最多读取的字节数,如果没有给定,则文件读取到末尾。 readline()方法读取打开文件的一行(读取下个行结束符之前的所有字节),然后整行,包括行结束符,作为字符串返回。 readlines()方法读取所有行然后把它们作为一个字符串列表返回
文件/home/pjc/python/pjc.txt的内容如下,分别使用上面的三个方法来读取,注意区别:
who i am?
I'm hehe
read()
1
2
3
4
5
6
7
>>> fobj = open('/home/pjc/python/pjc.txt') #默认以只读方式打开 >>> a = fobj.read()
>>> a
"who i am?\nI'm hehe\n" #直接读取字节到字符串中,包括了换行符
>>> print a
who i am?
I'm hehe
>>>>fobj.close()
#关闭打开的文件
readline():
1
2
3
4
5
6
7
8
>>> fobj = open('/home/pjc/python/pjc.txt')
>>> b = fobj.readline()
>>> b #读取整行,包括行结束符, 作为字符串返回
'who i am?\n'
>>> c = fobj.readline()
>>> c #读取整行,包括行结束符, 作为字符串返回 ,已经读到下一行了
"I'm hehe\n"
>>> fobj.close()
readlines():
1
2
3
4
5
6
7
>>> fobj = open('/home/pjc/python/pjc.txt')
>>> d = fobj.readlines()
>>> d
['who i am?\n', "I'm hehe\n"] #读取
所有行
然后把它们作为一个字符串列表返回
>>> fobj.close()