python生成器

1.处理文件,用户指定要查找的文件和内容,将文件中包含要查找内容的每一行都输出到屏幕

复制代码
# def find(str):
#     with open('test',mode='r',encoding='utf-8') as f:
#         for line in f:
#             if str in line:
#                 yield line.strip()
# str = input('')
# g = find(str)
# # print(list(g))
# for i in g:
#     print(i)
复制代码

2.写生成器,从文件中读取内容,在每一次读取到的内容之前加上‘***’之后再返回给用户。

def find():
    with open('test',mode='r',encoding='utf-8') as f:
        for line in f:
            yield '***'+line.strip()
g = find()
# print(list(g))
for i in g:
    print(i)

 

posted @   ‘哦耶’  阅读(111)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示