Python,检查数据文件中的特定行
我从来没有上过用Python的课,只学过C、C++、C#、Java等等。
这应该很简单,但我感觉我好像漏掉了Python中某个重要的东西。
我现在做的就是打开一个文件,检查哪些行只有数字,数一下这样的行有多少,并把结果显示出来。
所以我在打开文件、读取内容、去掉空格、检查是否是数字、然后计数。这样做有什么问题吗?
# variables
sum = 0
switch = "run"
print( "Reading data.txt and counting..." )
# open the file
file = open( 'data.txt', 'r' )
# run through file, stripping lines and checking for numerics, incrementing sum when neeeded
while ( switch == "run" ):
line = file.readline()
line = line.strip()
if ( line.isdigit() ):
sum += 1
if ( line == "" ):
print( "End of file\ndata.txt contains %s lines of digits" %(sum) )
switch = "stop"
5 个回答
0
你是怎么运行这个程序的?你确定data.txt文件里有数据吗?文件里有没有空行?
试试这个:
while 1:
line = file.readline()
if not line: break
line = line.strip()
if ( line.isdigit() ):
sum += 1
print( "End of file\ndata.txt contains %s lines of digits" %(sum) )
2
sum=0
f=open("file")
for line in f:
if line.strip().isdigit():
sum+=1
f.close()
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。
4
在Python中,判断文件是否读到头的方法不是看是否返回了空行。
正确的做法是遍历文件中的所有行,当到达文件末尾时,循环会自动结束。
num_digits = 0
with open("data.txt") as f:
for line in f:
if line.strip().isdigit():
num_digits += 1
因为文件是可以被遍历的,你可以用生成器表达式来简化这个过程:
with open("data.txt") as f:
num_digits = sum( 1 for line in f if line.strip().isdigit() )
我还建议不要把Python的保留关键字,比如sum
,用作变量名。此外,像你现在这样用字符串比较来控制流程也是非常低效的。