假设某文件名叫nba.txt ,里面的内容如下:
在python 2.6下
1
2
3
4
|
>>>
file
=
open
(
"文件路径/nba.txt"
,
"r"
)
>>>
for
i
in
range
(
5
):
name
=
file
.
next
print
(name)
|
输出结果如下:
在python 3.5下:
1
2
3
4
|
>>>
file
=
open
(
"文件路径/nba.txt"
,
"r"
)
>>>name
=
file
.readline()
>>>
print
(name)
lebron james
|
只显示第一行,即使再刷新print(name),也是lebron james这句话而不会是第二句。
1
2
3
4
|
>>>
file
=
open
(
"文件路径/nba.txt"
,
"r"
)
>>>
for
i
in
range
(
6
):
name
=
file
.readline()
print
(name)
|
输出就是:
lebron james
kobe bryant
allen iverson
steven curry
yao ming
#这里有一个空行
如果在3.5里使用.next()是不能搭配open函数的,会报错:AttributeError: '_io.TextIOWrapper' object has no attribute 'next'
那么在3.5里应该这么写:
1
2
3
4
|
with
open
(
"文件路径/nba.txt"
) as
file
:
while
True
:
name
=
next
(
file
)
print
(name)
|
这样就是输出全文。
本文转自 苏幕遮618 51CTO博客,原文链接:http://blog.51cto.com/chenx1242/1768031