Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将文本从一个文件传输到另一个文件-Python_Python_File Io - Fatal编程技术网

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

将文本从一个文件传输到另一个文件-Python,python,file-io,Python,File Io,我正试图编写一个程序,逐行读取名为“all_years.txt”(满年)的文件,并计算一年是否为闰年。如果是这样,我想把那一年写进另一个名为“leap_years.txt”的空文件中 这是我到目前为止掌握的代码,我就是搞不懂这个。老实说,我快疯了。我对编程不是很有经验,所以我很感激你能为我做一些这方面的工作 # calculation function def leapYear(year): """ Calculates whether a year is or isn't a leap

我正试图编写一个程序,逐行读取名为“all_years.txt”(满年)的文件,并计算一年是否为闰年。如果是这样,我想把那一年写进另一个名为“leap_years.txt”的空文件中

这是我到目前为止掌握的代码,我就是搞不懂这个。老实说,我快疯了。我对编程不是很有经验,所以我很感激你能为我做一些这方面的工作

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

修改以下行

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


当您使用“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()
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)
因此,如果
all_years.txt
包含:

2001
2002
2010
1900
1904年世界博览会
1946
1984
2000
2004年是闰年
您将获得包含以下内容的
leap_years.txt

1904年世界博览会
1984
2000
2004年是闰年

只打开文件一次,在for循环中只写闰年,一旦您遍历了所有行,即for循环结束,请关闭文件。另一件事是在您的leapYear()函数中,将year更改为int-typeOk谢谢,但是我应该提到,文件中还有字母。我如何让程序忽略字母?看起来是这样的:2001年2002年2010年1900年1904年世界博览会19年1946年1984年2000整个文本都在一行吗?不,对不起。每行一个,但正如你所看到的,有些行有字母。我试图让它只输出闰年,而忽略混音中的所有单词或字母。现在检查,isdigit()将完成这项工作leapYear函数中还有一个错误。它将str作为参数,因此引发TypeError
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)