0

所以我有一个问题需要这个功能:颜色,大小,肉和类用空格分隔。编写一个 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()
4

2 回答 2

0

也许你可以去掉print里面ofile.write

ofile.write(print("Animals = \n", animals))

ofile.write("Animals = \n" + str(animals))
于 2013-11-08T03:20:19.580 回答
0

您的缩进完全搞砸了程序。最大的罪犯是这个部分:

except IOError:
    print("Error reading file! Program ends here")
    endofprogram = True
    if (endofprogram == False):

if行只会在该endofprogram = True行之后立即执行,此时endofprogram == False将为假,因此if块中的任何内容(包括程序的其余部分)都将被执行。您需要将所有内容从头if开始降低一个级别。

于 2013-11-08T03:24:04.757 回答