Do I have an error in my loop?

70 Views Asked by At

I want to read an entire file "all_years.txt." (full of years/letters/words), line by line, and calculate if a year is a leap year. If so, I want to write that line into a different file that's empty called "leap_years.txt".

# calculation function
def leapYear(year):
    """ Calculates whether a year is or isn't a leap year. """
    year = int(year)
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

# main function
def main():
    try:
        file_1 = open("all_years.txt", "r") # open file
        lines = file_1.readlines()
        file_1.close()

        file_2 = open("leap_years.txt", "a") # open file

        for line in lines:
            if line.isdigit():
                if leapYear(line):
                    file_2.write(line)
        file_2.close()
    except ValueError as e:
        print(e)
main()

This code does in fact, read the first file and prints to the other empty file, but it only prints "6464" which is the last line on the "all_years.txt" file. Why doe sit only print the last file??

It's supposed to ignore all of the letters in the file. This is what the last 20 or so lines look on the "all_years.txt" file:

Lemming
2500
xyzw
2100
2101
2102
love
hate
3232
2054
2.71828
6504
6500
4242
1522
0.68
3333
666
325
1066
6464
1

There are 1 best solutions below

0
On

All of your lines except for the last line contain newlines, so isdigit returns false. Use strip on strings to remove whitespace from the ends. You can do it all in one place with a list comprehension:

lines = [line.strip() for line in file_1.readlines()]