概述
在用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 aaaaaaaaaaaaaaaaaaaaan2 bbbbbbbbbbbbbbbbbbbbbn3 cccccccccccccccccccccn4 ddddddddddddddddddddddn'
>>> 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 aaaaaaaaaaaaaaaaaaaaan'
>>> obj.readline()
'2 bbbbbbbbbbbbbbbbbbbbbn'
>>> obj.readline()
'3 cccccccccccccccccccccn'
>>> obj.readline()
'4 ddddddddddddddddddddddn'
>>> 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 aaaaaaaaaaaaaaaaaaaaan', '2 bbbbbbbbbbbbbbbbbbbbbn', '3 cccccccccccccccccccccn', '4 ddddddddddddddddddddddn']
>>> obj.readlines()
[]
>>> obj.readlines()
[]
>>>
触类旁通,还有write、writelines方法,用法与上述方法对应类似,只不过write写入的对象时字符串(str),writelines写入的是列表(list),即:
obj.write(str)
obj.writelines(sequence)
最后
以上就是大力宝马为你收集整理的python的read_Python中read,readline的全部内容,希望文章能够帮你解决python的read_Python中read,readline所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复