不用for loop循环一个读取一个文件

怎样在不使用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
原文地址:https://www.cnblogs.com/Andy963/p/7003144.html