python的输入输出程序

2024-10-01 15:33:04 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个问题,需要这个特性:颜色、大小、肉和类是用空格隔开的。编写一个Python程序,询问用户输入文件的名称(在本例中动物.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()

Tags: and程序inputlinefilewriteprint动物
2条回答

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

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

^{pr2}$

你的缩进完全把程序搞砸了。最大的违规者是这一部分:

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

if行只会在endofprogram = True行之后执行,此时endofprogram == False将为false,因此if块中的任何内容(包括程序的其余部分)。从if开始,你需要把所有的东西都删除一级。在

相关问题 更多 >

    热门问题