【发布时间】:2013-11-08 03:12:48
【问题描述】:
所以我有一个问题需要这个功能:颜色、大小、肉和类由空格分隔。编写一个 Python 程序,询问用户输入文件(在本例中是 animals.txt)和输出文件(任何名称)的名称。程序读入输入文件的行,忽略注释行(以 # 开头的行)和空白行,并计算并打印以下问题的答案: 动物总数? 危险动物的总数? 安全的大型动物有多少? 棕色和危险的动物数量? 有多少安全的红色或硬肉动物?
所以我完成了程序,一切似乎都在工作,但到目前为止,当我输入代码并启动程序时,一切正常,没有错误,除了没有生成输出文件之外什么都没有。我不知道到底出了什么问题,但如果有人能指出我正确的方向,我将不胜感激。
import os.path
endofprogram = False
try:
filename1 = input("Enter the name of input file: ")
filename2 = input("Enter the name of output file: ")
while os.path.isfile(filename2):
filename2 = input("File Exists! Enter new name for output file: ")
infile = open(filename1, 'r')
ofile = open(filename2, "w")
except IOError:
print("Error reading file! Program ends here")
endofprogram = True
if (endofprogram == False):
alist = []
blist = []
clist = []
largesafe = 0
dangerous = 0
browndangerous = 0
redhard = 0
for line in infile:
line = line.strip("\n")
if (line != " ") and (line[0] != "#"):
colour, size, flesh, clas = line.split('\t')
alist = alist.append(colour)
animals = alist.count()
while clas == "dangerous":
dangerous = dangerous + 1
while size == "large" and clas == "safe":
largesafe = largesafe + 1
while colour == "brown" and clas == "dangerous":
browndangerous = browndangerous + 1
while colour == "red" and flesh == "hard":
redhard = redhard + 1
ofile.write(print("Animals = \n", animals))
ofile.write(print("Dangerous = \n", dangerous))
ofile.write(print("Brown and dangerous = \n", browndangerous))
ofile.write(print("Large and safe = \n", largesafe))
ofile.write(print("Safe and red color or hard flesh= \n", redhard))
infile.close()
ofile.close()
【问题讨论】:
-
这与您在程序中的缩进是否相同?如果没有,您需要修复它。
-
一行一行。我什至只是使用 C 中的 diff 进行检查,没有任何区别,并且完全相同。