不用for loop循環一個讀取一個文件
阿新 • • 發佈:2017-09-28
stop print efault 文件 ati 循環 bre txt don
怎樣在不使用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循環一個讀取一個文件