生成一个 10 行的文本文件,每一行以 "\n" 结尾,统计行数为 10 。
def generate_file():
with open("line.log", "w") as f:
for i in range(1, 10+1):
f.write(f"Line is: your target line{i} to print\n")
def chunked_file_reader(fp, block_size=4 * 1024):
while True:
chunk = fp.read(block_size)
if not chunk:
break
yield chunk
def get_line_count(fname):
count = 0
with open(fname) as fp:
for chunk in chunked_file_reader(fp):
count += chunk.count("\n")
return count
generate_file()
line_count = get_line_count("line.log")
# > 10
block_size 亦或者说 buffering 传入的大小是每一行的长度,count 结果会变成 9 ,求解
def return_count(fname):
count = 0
with open(fname) as fp:
line = fp.readline()
for chunk in chunked_file_reader(fp, len(line)):
count += chunk.count("\n")
return count
generate_file()
line_count = get_line_count("line.log")
# > 9
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.