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迭代器和文件迭代相關知識的介紹,但願對初學者學習相關知識有所幫助。

相關文章
相關標籤/搜索