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)
原文地址:https://www.cnblogs.com/aizh/p/11145349.html