Python程序不会创建输出文件

时间:2013-11-08 05:07:22

标签: python file input output

所以我正在编写一个程序来读取文件,接受一些输入,然后将结果输出到文件中,但不管我做什么,我似乎无法让输出文件真正出现。任何帮助将不胜感激。这是我的代码

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()

2 个答案:

答案 0 :(得分:1)

在try块之后发表if语句:

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
    ...

答案 1 :(得分:0)

import os.path #Needs to be just os, not just that.