forumer444
forumer444

Reputation: 35

Transferring text from one file to another - Python

I'm trying to write a program that reads a file called "all_years.txt" (full of years), line by line, and calculates whether a year is a leap year or not. If so, I want to write that year into a different file that's empty called "leap_years.txt".

This is code I have so far and I just can't figure this one out. It's driving me crazy honestly. I'm not very experienced with programming, so I'd appreciate the some with this one.

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

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

        for line in lines:
            if leapYear(line):
                file2 = open("leap_years.txt", "w")
                file2.write(line)
                file2.close()
    except ValueError as e:
        print(e)

main()

Upvotes: 0

Views: 48

Answers (3)

Martin Evans
Martin Evans

Reputation: 46789

I suggest you keep both files open and read your input file line by line. You would need to use a regular expression to try and extract a number from the line. In this case it extracts just the first number it finds, so you would need to think what to do if there was more than one on a line:

import re

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

with open('all_years.txt') as f_input, open('leap_years.txt', 'w') as f_output:
    for line in f_input:
        year = re.search(r'\b(\d+)\b', line)

        if year and leapYear(int(year.group(1))):
            f_output.write(line)

So if all_years.txt contained:

2001 
2002 
2010 
1900 
1904 World's Fair 19ol 
1946 
1984 
2000 
Year 2004 is a leap year

You would get leap_years.txt containing:

1904 World's Fair 19ol 
1984 
2000 
Year 2004 is a leap year

Upvotes: 1

Bhawan
Bhawan

Reputation: 2501

# 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 = open("all_years.txt", "r")
        lines = file.readlines()
        file.close()

        file2 = open("leap_years.txt", "w")

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

main()

Upvotes: 0

Max
Max

Reputation: 1363

modify the following line

file2 = open("leap_years.txt", "w")

to

file2 = open("leap_years.txt", "a")

when you use "w", it will create a new file every time.

Upvotes: 0

Related Questions