gpt4 book ai didi

python - 在 python 3 中读取和写入文件

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:49 25 4
gpt4 key购买 nike

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。我不知道从哪里开始回答后面的两个问题。

最佳答案

你应该逐行处理文件,这比读取整个文件更容易,比如:

infile = open('entrada', 'r')

animals = 0
safe_animals = 0
dangerous_animals = 0

for line in infile:
line_components = line.strip().split()
if line_components:
animals += 1

if line_components[3] == 'dangerous':
dangerous_animals += 1
elif line_components[3] == 'safe' and line_components[1] == 'large':
safe_animals += 1

print "%i animals" % animals
print "%i safe animals" % safe_animals
print "%i dangerous animals" % dangerous_animals

关于python - 在 python 3 中读取和写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19824986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com