自學Python之路-Python基礎+模塊+面向對象
自學Python之路-Python網絡編程
自學Python之路-Python併發編程+數據庫+前端
自學Python之路-djangohtml
此時在file文件裏面輸入內容,在生成器執行裏面能夠看到file的內容,且後續一直爲空,程序一直在執行,只是讀出的數據是空。前端
進一步,若是line不爲空纔打印python
f = open("file",encoding="utf-8") while True: line = f.readline() if line: print(line)
進一步,取消執行器看到的空格數據庫
f = open("file",encoding="utf-8") while True: line = f.readline() if line: print(line.strip())
如何用生成器實現:
django
def tail(filename): f = open(filename,encoding="utf-8") while True: line = f.readline() if line.strip(): print(line.strip()) tail('file')
打印監聽每行字前面加******編程
監聽每行字若是有python纔打印, 實現監聽過濾功能。網絡
def check_file(filename,aim): with open(filename,encoding='utf-8') as f: #句柄 : handler,文件操做符,文件句柄 for i in f: if aim in i: yield i g = check_file('test.01','生成器') for i in g: print(i.strip())
將文件test.01裏面含有"生成器"的行數打印出來:
併發
def check_file(filename): with open(filename,encoding='utf-8') as f: #句柄 : handler,文件操做符,文件句柄 for i in f: yield '***'+i for i in check_file('test.01'): print(i.strip())
......post