gpt4 book ai didi

python 2.7 文件困难

转载 作者:行者123 更新时间:2023-11-28 16:25:40 25 4
gpt4 key购买 nike

我试图创建一个程序来计算动物(熊、狼等)的数量并将它们放入变量中。

这是行不通的

import os
def count_species():
sal_count = 0
tro_count = 0
filename1 = animals.txt
if os.path.exists(animals.txt):
f = open(filename1, 'r')
for line in f:#will execute each line in the file individually
if line == 'Salmon':
sal_count +=1
if line == 'Trout':
tro_count += 1

出于某种原因,程序没有记录第一行 == Salmon。其他一切似乎都有效。该文件的示例如下所示

Salmon
Trout
Salmon

这是怎么回事?

最佳答案

您正在读入文件,遍历文件行并检查:

if line == 'Salmon':
....
if line == 'Trout':
....

该行不一定是这个,它可以在末尾有换行符(它会在这里)。读入文件并去掉换行符。

一种方法:

with open(path to file, "r") as f:
lines = [x.strip() for x in f]
....

您也永远不会关闭该文件。使用上下文管理器,您不必担心关闭它,一切都已为您处理。

此外,您可能不想在这里使用两个 if 语句。

关于python 2.7 文件困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36974502/

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