我的循环中有错误吗?

时间:2017-09-17 00:22:21

标签: python file loops try-except

我想读一整个文件“all_years.txt”。 (逐年/字母/单词),逐行,并计算一年是否是闰年。如果是这样,我想把那行写成一个空的名为“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()

这段代码实际上是读取第一个文件并打印到另一个空文件,但它只打印“6464”,这是“all_years.txt”文件的最后一行。为什么只能打印最后一个文件?

它应该忽略文件中的所有字母。 这是“all_years.txt”文件中最后20行左右的内容:

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

1 个答案:

答案 0 :(得分:1)

除最后一行之外的所有行都包含换行符,因此isdigit返回false。在字符串上使用strip可以从末尾删除空格。您可以使用列表理解在一个地方完成所有操作:

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

相关问题