我有以下文件my_animals.txt,其中包含字符串列表:
cat
dog
bear
wolf
flamingo
parrot
我正在使用Python将文件读入一个集合,my_animals.txt中的每一行都作为集合的元素:
my_animals = set()
# read in file
with open('my_animals.txt', 'rb') as f:
for animal in f:
my_animals.add(animal.rstrip("\n"))
# check for membership
if "cat" in my_animals:
print True
else:
print False
不幸的是,我的会员资格检查正在返回False
。我哪里错了?
答案 0 :(得分:1)
我建议您采用不同的方法来处理您目前正在做的事情。首先,以文本模式打开文件:
with open('my_animals.txt', 'r') as f:
此外,使用my_animals.add(animal.rstrip())
,换行符将自动与任何其他空格字符一起被删除。这在Windows上很有用,例如,行由\r\n
分隔。
答案 1 :(得分:0)
您编写的代码是正确的,正如评论中提到的那样,您可以删除“b”以便不以二进制模式读取文件。您可以使用较小的文件进行测试,以确保是这种情况。
顺便说一句:如果您的文件是1GB(正如您在评论中提到的那样),请不要将整个内容加载到一个集合中,除非您确定有足够的内存来执行此操作!