[英]Input and Output program for python
所以我有一個問題需要此功能。顏色,大小,果肉和類別由空格分隔。 編寫一個Python程序,詢問用戶輸入文件的名稱(在本例中為animal.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()
也許您可以在ofile.write
刪除print
ofile.write
ofile.write(print("Animals = \n", animals))
至
ofile.write("Animals = \n" + str(animals))
您的縮進完全把程序弄亂了。 最大的罪犯是本節:
except IOError:
print("Error reading file! Program ends here")
endofprogram = True
if (endofprogram == False):
if
行僅在endofprogram = True
行之后立即執行,此時endofprogram == False
將為false,因此if
塊中(包括程序的其余部分)將不執行任何操作。 您需要將if
以后的所有內容降低一級。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.