【发布时间】:2013-11-08 05:07:21
【问题描述】:
所以我正在编写一个程序来读取文件,获取一些输入,然后将结果输出到文件中,但无论我做什么,我似乎都无法让输出文件真正出现。任何帮助将不胜感激。这是我的代码
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()
【问题讨论】:
-
您实际上没有任何代码可以输出文件。
-
你从哪里得到的代码? :)
-
不就是ofile = open(filename2, "w") 和ofile.write("Animals = \n" + str(animals)) ofile.write("Dangerous = \n" + str(dangerous)) ofile.write("棕色和危险 = \n" + str(browndanger)) ofile.write("大而安全 = \n", + str(largesafe)) ofile.write( "安全红色或硬肉= \n", + str(saferedhard)) 还是我根本不懂python I/O。
-
@alko 我自己写的。为什么要问?
-
发布的代码应该简短、独立且可编译 (sscce.org)。这个例子很简短。请重写。