安迪_963

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

怎样在不使用for loop的情况下循环读取一个文件并将内容显示出来呢?

#!/usr/bin/env python
#coding:utf-8
#@Author:Andy
# Date: 2017/6/13

"""
if you want to process an iterable object ,but you don't want to use loop
"""
# method 1
with open('test.txt') as f:
	try:
		while True:
			line = next(f)
			print(line, end=' ')
	except StopIteration:
		exit()

# method 2
with open('test.txt') as f:
	while True:
		line = next(f, None) # None is default ,if you don't set this value ,it'll raise StopIteration
		if not line:
			break
		print(line, end=' ')


if __name__ == '__main__':
	pass

 

posted on 2017-09-28 00:29  Andy_963  阅读(406)  评论(0编辑  收藏  举报