Files
Python_CookBook_repo/4.迭代器与生成器/16.用迭代器取代while循环.py
2025-09-10 16:12:45 +08:00

34 lines
778 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == "__main__":
CHUNKSIZE = 10
def render(s):
# 军火展示
print(s.read())
s.seek(0)
# 在处理文件的时候我们习惯用while循环来迭代数据
print("一般while处理")
while True:
data = s.read(CHUNKSIZE)
if data == b'':
break
print(data)
s.seek(0)
# 但是可以使用迭代器来升级一下
print("进化成迭代器:")
for chunk in iter(lambda: s.read(CHUNKSIZE), b''):
print(chunk)
path = "4.迭代器与生成器/16.test.txt"
# 二进制打开文件记得用rb下一章进化一下文件读取方面的知识
f = open(path, 'rb')
render(f)
print("Done")