跟老齐学Python之让人欢喜让人忧的迭代

2019-10-05 16:50:37丽君

文件迭代器

现在有一个文件,名称:208.txt,其内容如下:


Learn python with qiwsir.
There is free python course.
The website is:
http://qiwsir.github.io
Its language is Chinese.

用迭代器来操作这个文件,我们在前面讲述文件有关知识的时候已经做过了,无非就是:


>>> f = open("208.txt")
>>> f.readline()        #读第一行
'Learn python with qiwsir.n'
>>> f.readline()        #读第二行
'There is free python course.n'
>>> f.readline()        #读第三行
'The website is:n'
>>> f.readline()        #读第四行
'http://qiwsir.github.ion'
>>> f.readline()        #读第五行,也就是这真在读完最后一行之后,到了此行的后面
'Its language is Chinese.n'
>>> f.readline()        #无内容了,但是不报错,返回空。
''

以上演示的是用readline()一行一行地读。当然,在实际操作中,我们是绝对不能这样做的,一定要让它自动进行,比较常用的方法是:


>>> for line in f:     #这个操作是紧接着上面的操作进行的,请看官主要观察
...     print line,    #没有打印出任何东西
...

这段代码之所没有打印出东西来,是因为经过前面的迭代,指针已经移到了最后了。这就是迭代的一个特点,要小心指针的位置。


>>> f = open("208.txt")     #从头再来
>>> for line in f:
...     print line,
...
Learn python with qiwsir.
There is free python course.
The website is:
http://qiwsir.github.io
Its language is Chinese.

这种方法是读取文件常用的。另外一个readlines()也可以。但是,需要有一些小心的地方,看官如果想不起来小心什么,可以在将关于文件的课程复习一边。

上面过程用next()也能够读取。


>>> f = open("208.txt")
>>> f.next()
'Learn python with qiwsir.n'
>>> f.next()
'There is free python course.n'
>>> f.next()
'The website is:n'
>>> f.next()
'http://qiwsir.github.ion'
>>> f.next()
'Its language is Chinese.n'
>>> f.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

如果用next(),就可以直接读取每行的内容。这说明文件是天然的可迭代对象,不需要用iter()转换了。