如何将文本文件中的数据转换为列表?
我的目标是打开狗档案,将它转换成列表,然后让使用者输入狗的类型,如果它与狗列表中的狗名称相符,则说它是正确的。如何将文本文件中的数据转换为列表?
dog_file = open("Dogs.txt", "r")
dogs = dog_file.readlines()
print(dogs)
data = input("Enter a name: ")
if data == dogs:
print("Success")
else:
print("Sorry that didn't work")
dogs
是一个字符串列表,而data
是一个字符串。你想使用in
操作,以检查是否data
包含在dogs
:
if data in dogs:
# do sth
事情是当我键入一个答案时,我得到了else语句的结果。 –
也许在每行末尾有\ n或\ r这样的空格字符,试试:'dog = [dog.strip()for dog_file.readlines()]' – Leistungsabfall
是的,谢谢你们。 –
试试这个:
dog_list = []
for dog in dogs:
dog_list.append(dog)
这将文件的每一行追加到一个列表。我们检查是否有列表中的尝试狗:
dog_type = input("Enter a dog: ")
if dog_type in dog_list":
print("Success")
如果您想将.TXT写入到一个数组(转换列出),试试这个:
with open("Dogs.txt", "r") as ins:
dogarray = []
for line in ins:
line = line.strip()
dogarray.append(line)
print (dogarray)
这会将它成一个数组,并使用.strip
函数在每一行新行后删除不需要的\n
。你现在需要做的就是从数组中读取数据。
试试这个:
dog_file = open("Dogs.txt", "r")
dogs = dog_file.readlines()
# you want to strip away the spaces and new line characters
content = [x.strip() for x in dogs]
data = input("Enter a name: ")
# since dogs here is a list
if data in dogs:
print("Success")
else:
print("Sorry that didn't work")
'如果数据== dogs'不会因为你针对一个列表平等的测试工作。也许'如果数据在狗' – roganjosh
你几乎在那里。只需更改'if'检查。 '如果数据+'\ n'在狗中:' – balki