我编写的程序使用文本文件的值进行一些计算,并打印结果。但是,另外,我希望看到有多少的文本文件是通过完成的。
我的文本文件有629行,所以我希望我的程序计算行数,除以629,然后乘以100,然后继续显示它已经通过的总行数的百分比。但我该怎么做呢?
我试过:
num_lines = sum(1 for line in open('myfile.txt'))
percentage = 100*num_lines / 629
print percentage, '%'
但是,当它已经遍历了整个文本文件时,它才返回'100%'
,但是我希望它从0%开始,然后进行到100%
。
我是刚接触python的人,我非常感谢您的帮助。
发布于 2015-03-02 06:28:32
加强彼得·伍德的回答
# get total lines of the input file
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
f = 'file.txt'
total = file_len(f)
num_lines = 0
for line in open(f):
num_lines += 1
percentage = 100 * num_lines / total
print percentage, '%'
https://stackoverflow.com/questions/28811575
复制相似问题