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

Posted 安迪_963

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了不用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

 

以上是关于不用for loop循环一个读取一个文件的主要内容,如果未能解决你的问题,请参考以下文章