所以我有一个问题需要这个功能:颜色,大小,肉和类用空格分隔。编写一个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()
答案 0 :(得分:0)
也许您可以删除print
ofile.write
ofile.write(print("Animals = \n", animals))
到
ofile.write("Animals = \n" + str(animals))
答案 1 :(得分:0)
你的缩进完全搞砸了程序。最大的罪犯是这一部分:
except IOError:
print("Error reading file! Program ends here")
endofprogram = True
if (endofprogram == False):
if
行只会在endofprogram = True
行之后立即执行,此时endofprogram == False
将为false,因此if
块中没有任何内容 - 包含程序的其余部分 - 将被执行。你需要将if
以后的所有内容都放在一个层面上。