Python文件迭代的用法实例教程

python开发中,咱们经常都会用到迭代器,因此对于python初学者来讲,必须掌握迭代器相关知识。本文小编就将为你们分享有关迭代器的相关知识,以为有必要了解或加深了解的童鞋,请往下看。python

1.迭代器介绍
可迭代对象:列表、元组、字符串
迭代工具:for循环、列表解析、in成员关系测试、map内建函数
下面,经过具体的例子,给你们展现一下:shell

1. >>> for item in (1,3,4,5):函数

2.   print(item)工具

3. 性能

4. 1学习

5. 3测试

6. 4spa

7. 5对象

8. >>> for alpha in 'abcde':内存

9.   print(alpha)

10. 

11. a

12. b

13. c

14. d

15. e

16. >>> for item in [1,2,3,4]:

17.   print(item)

18. 

19. 

20. 1

21. 2

22. 3

23. 4

24. >>>

上面的例子都是使用for循环结合in成员关系测试来迭代列表、元组与字符串。

2.文件迭代器
说到文件迭代,咱们经常将for与readline结合起来使用,好比:

1. >>> handler=open('output_file.txt')

2. >>> handler.readline()

3. 'abcd\n'

4. >>> handler.readline()

5. 'efgh\n'

6. >>> handler.readline()

7. 'ijklstrstr\n'

8. >>> handler.readline()

9. 'nn'

10. >>> handler.readline()

11. ''

12. >>> handler=open('output_file.txt')

13. >>> for line in handler.readlines():

14.   print(line)

15. 

16. abcd

17. 

18. efgh

19. 

20. ijklstrstr

21. 

22. nn

23. >>>

在上面的这个例子中,须要注意的一点就是,第一个程序一直调用handler.readline(),若是到了末尾,一直返回空的话,使用for加上handler.readlines(),若是到达底部,则直接中止。

在文件里面,其实还有有一个内建函数next能够达到上面的相似效果:

1. >>> handler=open('output_file.txt')

2. >>> handler.__next__ ()

3. 'abcd\n'

4. >>> handler.__next__ ()

5. 'efgh\n'

6. >>> handler.__next__ ()

7. 'ijklstrstr\n'

8. >>> handler.__next__ ()

9. 'nn'

10. >>> handler.__next__ ()

11. Traceback (most recent call last):

12.   File "<pyshell#35>", line 1, in <module>

13.     handler.__next__ ()

14. StopIteration

15. >>> handler.close ()

16. >>>

可是使用next函数实现这个效果的时候,须要注意的是,到达底部,会自动报错。next()是经过捕捉StopIteration来肯定是否离开。

最后,咱们来看看文件迭代性能问题:
1.当文件过大的时候怎么读取(超过100M)
这种状况下就不能使用handler.readlines()方法了,由于handler.readlines()是一次性把整个文件加载到内存里面去的。

在这种状况下,通常是一行行的来读取,可参考下面两种方法实现:

1. >>> for line in handler:

2.   print(line,end='')

3. abcd

4. efgh

5. ijklstrstr

6. nn

7. >>>

8. 

9. 

10. 

11. 

12. >>> handler=open('output_file.txt')

13. >>> while True:

14.   line=handler.readline()

15.   if not line:

16.     break

17.   print(line,end='')

18. abcd

19. efgh

20. ijklstrstr

21. nn

22. >>> handler.close ()

23. >>>

在上面这两种方法中,建议使用第一种for…in…方法,由于这种方法相比而言更快捷、简洁。

以上就是python迭代器和文件迭代相关知识的介绍,但愿对初学者学习相关知识有所帮助。

相关文章
相关标签/搜索