开发者

Python, checking data file for certain lines

开发者 https://www.devze.com 2023-02-08 05:45 出处:网络
I\'ve never taken a class that used python, just c, c++, c#, java, etc.. This should be easy but I\'m feeling like I\'m missing something huge that python reacts to.

I've never taken a class that used python, just c, c++, c#, java, etc.. This should be easy but I'm feeling like I'm missing something huge that python reacts to. All I'm doing is reading in a file, checking for lines that are only digits, cou开发者_如何学Cnting how many lines like that and displaying it.

So I'm opening, reading, striping, checking isdigit(), and incrementing. What's wrong?

# 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"


The correct way in Python to tell if you've reached the end of a file is not to see if it returns an empty line.

Instead, iterate over all the lines in the file, and the loop will end when the end of the file is reached.

num_digits = 0
with open("data.txt") as f:
    for line in f:
        if line.strip().isdigit():
            num_digits += 1

Because files can be iterated over, you can simplify this using a generator expression:

with open("data.txt") as f:
   num_digits = sum( 1 for line in f if line.strip().isdigit() )

I would also recommend against using reserved Python keywords such as sum as variable names, and it's also terribly inefficient to use string comparisons for flow logic like you're doing.


sum=0
f=open("file")
for line in f:
    if line.strip().isdigit():
         sum+=1
f.close()  


I just tried running your code:

matti@konata:~/tmp$ cat data.txt 
1
a
542
dfd
b
42
matti@konata:~/tmp$ python johnredyns.py 
Reading data.txt and counting...
End of file
data.txt contains 3 lines of digits

It works fine here. What's in your data.txt?


As several people have said, your code appears to work perfectly. Perhaps your "data.txt" file is in a different directory than your current working directory (not necessarily the directory that your script is in)?

However, here's a more "pythonic" way of doing the same thing:

counter = 0
with open('data.txt', 'r') as infile:
    for line in infile:
        if line.strip().isdigit():
            counter += 1
print 'There are a total of {0} lines that start with digits'.format(counter)

You could even make it a one-liner with:

counter = sum([line.strip().isdigit() for line in open('data.txt', 'r')])

I'd avoid that route at first though... It's much less readable!


How are you running the program? Are you sure data.txt has data? Is there an empty line in the file?

try this:

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) )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号