【发布时间】:2017-09-17 00:22:21
【问题描述】:
我想阅读整个文件“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
【问题讨论】:
-
我应该说文本之间的每个空格都是文件上的一个新行......所以它基本上是你看到的垂直版本。
-
使用
line.strip().isdigit()去掉断线\n或者行中的空格,可能是这个问题 -
因为 isdigit 仅当字符串中的所有字符都是数字时才为真。空格和行尾不是数字。您也没有真正逐行阅读原始文件,但这可能并不重要,除非文件变大。
-
我几乎所有工作都正常,除了如果行中有年份之后的字母,即使是闰年也不会打印年份。我该如何解决?
-
# function def jumpYear(year): year = int(year) return year % 4 == 0 and (year % 10 != 0 or year % 400 == 0) # function def writeFile( ): for line in lines: if line.strip().isdigit(): if jumpYear(line): file_2.write(line) # 构造 try: file_1 = open("all_years.txt", "r") lines = file_1.readlines() file_1.close() file_2 = open("leap_years.txt", "w") writeFile() file_2.close() 除了 ValueError as e: print(e)
标签: python file loops try-except