我正在尝试编写一个程序,逐行读取一个名为“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()
答案 0 :(得分:1)
我建议您保持两个文件都打开并逐行读取输入文件。您需要使用正则表达式尝试从行中提取数字。在这种情况下,它只提取它找到的第一个数字,所以如果一行中有多个数字,你需要考虑该怎么做:
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 World's Fair 19ol
1946
1984
2000
Year 2004 is a leap year
你会得到leap_years.txt
包含:
1904 World's Fair 19ol
1984
2000
Year 2004 is a leap year
答案 1 :(得分:0)
修改以下行
file2 = open("leap_years.txt", "w")
到
file2 = open("leap_years.txt", "a")
当你使用" w"时,它会每次都创建一个新文件。
答案 2 :(得分:0)
# 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()