简体   繁体   English

将文本从一个文件传输到另一个文件-Python

[英]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. 我正在尝试编写一个程序,逐行读取一个名为“ all_years.txt”(多年)的文件,并计算一年是否为a年。 If so, I want to write that year into a different file that's empty called "leap_years.txt". 如果是这样,我想将该年写入另一个名为“ 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()

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: 因此,如果all_years.txt包含:

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: 您将获得leap_years.txt其中包含:

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

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. 当您使用“ w”时,它将每次创建一个新文件。

# 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM