-3

そのため、ファイルを読み取り、入力を取り、結果をファイルに出力するプログラムを作成していますが、何をしても出力ファイルが実際に表示されないようです。どんな助けでも大歓迎です。これが私のコードです

import os.path
endofprogram = False

try:
    filename1 = input("Enter the name of input file: ")
    infile = open(filename1, 'r')
    filename2 = input("Enter the name of output file: ")
    if os.path.isfile(filename2) == True:
        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):
        dangerous = 0
        largesafe = 0
        animals = 0
        browndanger = 0
        saferedhard = 0
        for line in infile:
            line = line.strip("\n")
            if (line != " ") and (line[0] != "#"):
                lineparts = line.split()
                if lineparts:
                    animals = animals +1                    
                    if lineparts[3] == "dangerous":
                        dangerous = dangerous + 1
                    elif lineparts[1] == "large" and lineparts[3] == "safe":
                        largesafe = largesafe + 1
                    elif lineparts[0] == "brown" and lineparts[3] == "dangerous":
                        browndanger = browndanger + 1
                    elif (lineparts[0] == "red" )and ((lineparts[3] == safe) or (lineparts[2])):
                        saferedhard == saferedhard + 1


                ofile.write("Animals = \n" + str(animals))
                ofile.write("Dangerous = \n" + str(dangerous))
                ofile.write("Brown and dangerous = \n" + str(browndanger)) 
                ofile.write("Large and safe = \n", + str(largesafe))
                ofile.write("Safe and red color or hard flesh= \n", + str(saferedhard))

            infile.close()
            ofile.close()
4

2 に答える 2

1

iftry ブロックに続くステートメントをデデントします。

import os.path
endofprogram = False

try:
    ...
except IOError:
    print("Error reading file! Program ends here")
    endofprogram = True           
if (endofprogram == False): # This logic is independent of whether an error occurs.
    dangerous = 0
    ...
于 2013-11-08T05:12:25.167 に答える
0
import os.path #Needs to be just os, not just that.
于 2016-11-01T22:23:47.340 に答える