def bylineread(fimename):
    with open(fimename) as f:   # 打开文件
        line = f.readline() # 读取一行内容
        print('----1----')
        while line: 
            print('-----2----')
            yield line
            line = f.readline() #不断循环读取
            print('----3-----')
# # read是一个生成器对象
read = bylineread('data1.txt')
print(read)

1.next读取生成器内容

print(next(read))   # 读取data1两行内容
print(next(read))

python -通过yield实现文件的读取

2.for读取全部生成器内容

for item in read:
    print(item)

文件对象是可以for循环遍历的:

from collections import Iterable

f = open('data1.txt')
print(isinstance(f,Iterable))
for i,item in enumerate(f):	#打印前10行,i是计数器,item是遍历的内容
    if i == 10:
        break
    print(i,item)

python -通过yield实现文件的读取

相关文章:

  • 2021-11-23
  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-14
  • 2021-11-09
猜你喜欢
  • 2021-05-31
  • 2022-12-23
  • 2022-12-23
  • 2023-02-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案