在用python读取文件的时经常用到三read、readline、readlines三种方法,它们功能实质区别如下:
read 读取整个文件
readline 读取下一行
readlines 读取整个文件到一个迭代器以供我们遍历(读取到一个list中,以供使用,比较方便)
测试文件为test.txt内容为:1 aaaaaaaaaaaaaaaaaaaaa
2 bbbbbbbbbbbbbbbbbbbbb
3 ccccccccccccccccccccc
4 dddddddddddddddddddddd[root@node01 ~]# pwd
/root
[root@node01 ~]# ls -l test.txt
-rw-r--r-- 1 root root 97 Jan 20 10:59 test.txt
[root@node01 ~]# cat test.txt
1 aaaaaaaaaaaaaaaaaaaaa
2 bbbbbbbbbbbbbbbbbbbbb
3 ccccccccccccccccccccc
4 dddddddddddddddddddddd
read方法
[root@node01 ~]# python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> obj=open('/root/test.txt','r+w')
>>> obj.read()
'1 aaaaaaaaaaaaaaaaaaaaa\n2 bbbbbbbbbbbbbbbbbbbbb\n3 ccccccccccccccccccccc\n4 dddddddddddddddddddddd\n'
>>> obj.read()
''
>>> exit()
readline方法
[root@node01 ~]# python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> obj=open('/root/test.txt','r+w')
>>> obj.readline()
'1 aaaaaaaaaaaaaaaaaaaaa\n'
>>> obj.readline()
'2 bbbbbbbbbbbbbbbbbbbbb\n'
>>> obj.readline()
'3 ccccccccccccccccccccc\n'
>>> obj.readline()
'4 dddddddddddddddddddddd\n'
>>> obj.readline()
''
>>> exit()
readlines方法
[root@node01 ~]# python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> obj=open('/root/test.txt','r+w')
>>> obj.readlines()
['1 aaaaaaaaaaaaaaaaaaaaa\n', '2 bbbbbbbbbbbbbbbbbbbbb\n', '3 ccccccccccccccccccccc\n', '4 dddddddddddddddddddddd\n']
>>> obj.readlines()
[]
>>> obj.readlines()
[]
>>>
触类旁通,还有write、writelines方法,用法与上述方法对应类似,只不过write写入的对象时字符串(str),writelines写入的是列表(list),即:
obj.write(str)
obj.writelines(sequence)