假设某文件名叫nba.txt ,里面的内容如下:

wKiom1cfUfbBsUlKAAAlnrmz_hY842.png

python 2.6

1
2
3
4
>>> file = open ( "文件路径/nba.txt" "r" )
>>> for  in  range ( 5 ):
     name = file . next
     print (name)

输出结果如下:

wKioL1cfU2zwrPYqAAAc7c7ngnM122.png

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  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)

这样就是输出全文。