Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 2.7 difficulty with files

I am attempted to create a program that counts the amount of animals (bear, wolf, etc) and put them into variables.

This is not working

import os
def count_species():
    sal_count = 0
    tro_count = 0
    filename1 = animals.txt
    if os.path.exists(animals.txt):
        f = open(filename1, 'r')
        for line in f:#will execute each line in the file individually
            if line == 'Salmon':
                sal_count +=1
            if line == 'Trout':
                tro_count += 1

For some reason the program does not register that the first line == Salmon. Everything else seems to work. An example of the file is seen below

Salmon
Trout
Salmon

What is going on?

like image 772
millahgn Avatar asked May 28 '26 21:05

millahgn


1 Answers

You're reading the file in, and iterating over the lines of the file and checking:

if line == 'Salmon':
    ....
if line == 'Trout':
    ....

The line may not necessarily be this, it could have newline characters at the end (which it will here). Read the file in and strip the newline characters out.

One way to do this:

with open(path to file, "r") as f:
     lines = [x.strip() for x in f]
     ....

You also never close the file. Using the context manager you don't have to worry about closing it everything's handled for you.

Also, you probably don't want to be using two if statements here.

like image 168
Pythonista Avatar answered May 30 '26 11:05

Pythonista



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!