import os.path
endofprogram=False
try:
filename1=input("Enter input file: ")
filename2=input("Enter output file: ")
while os.path.isfile(filename2):
filename2=input("File Exists! Enter new name for output file: ")
except IOError:
print("Error opening file - End of program")
endofprogram=True
if(endofprogram == False):
infile=open(filename1, "r")
content=infile.read()
lines=[]
words=[]
lines=content.split('\n')
print("Total animals=",len(lines))
多年来,我一直在研究这个与文件有关的程序。我有一个文件:
#color size flesh class
brown large hard safe
green large hard safe
red large soft dangerous
green large soft safe
red small hard safe
red small hard safe
brown small hard safe
green small soft dangerous
green small hard dangerous
red large hard safe
brown large soft safe
green small soft dangerous
red small soft safe
red large hard dangerous
red small hard safe
green small hard dangerous
我应该回答以下问题:
- 动物总数?
- 危险动物的总数?
- 安全的大型动物有多少?
到目前为止,我可以打印出动物的总数,但它包括空格以及我不想要的注释行。目前对于动物的总数,打印的是 19,而应该是 16。我不知道从哪里开始接下来的两个问题。