使用python读取txt文件并回答问题

使用python读取txt文件并回答问题,python,Python,所以我把这个数据列表作为一个txt文件,其中动物名称:date:location 所以我必须阅读这个txt文件来回答问题 到目前为止我已经 a01:01-24-2011:s1 a03:01-24-2011:s2 a02:01-24-2011:s2 a03:02-02-2011:s2 a03:03-02-2011:s1 a02:04-19-2011:s2 a01:05-14-2011:s2 a02:06-11-2011:s2 a03:07-12-2011:s1 a01:08-19

所以我把这个数据列表作为一个txt文件,
其中动物名称:date:location
所以我必须阅读这个txt文件来回答问题

到目前为止我已经

a01:01-24-2011:s1 
a03:01-24-2011:s2 
a02:01-24-2011:s2 
a03:02-02-2011:s2 
a03:03-02-2011:s1 
a02:04-19-2011:s2 
a01:05-14-2011:s2 
a02:06-11-2011:s2 
a03:07-12-2011:s1 
a01:08-19-2011:s1 
a03:09-19-2011:s1 
a03:10-19-2011:s2 
a03:11-19-2011:s1 
a03:12-19-2011:s2 

我知道如何读一行,但这里有多行,我不知道如何读txt中的每一行

对循环使用

text_file=open("animal data.txt", "r") #open the text file and reads it. 

如果
打开
失败,您可以使用
with
语句打开文件

text_file = open("animal data.txt","r")
for line in text_file:
    line = line.split(":")
    #Code for what you want to do with each element in the line
text_file.close()

您缺少关闭文件的命令。最好使用
with
语句来确保文件被关闭

>>> with open('data.txt', 'r') as f_in:
>>>     for line in f_in:
>>>         line = line.strip() # remove all whitespaces at start and end
>>>         field = line.split(':')
>>>         # field[0] = animal name
>>>         # field[1] = date
>>>         # field[2] = location

由于您知道此文件的格式,因此可以比其他答案更简短:

with open("animal data.txt","r") as file:
    for line in file:
        line = line.split(":")
        # Code for what you want to do with each element in the line
或者,如果您想保留从文件中获取的信息的数据库以回答您的问题,您可以执行以下操作:

with open('animal data.txt', 'r') as f:
    for line in f:
        animal_name, date, location = line.strip().split(':')
        # You now have three variables (animal_name, date, and location)
        # This loop will happen once for each line of the file
        # For example, the first time through will have data like:
        #     animal_name == 'a01'
        #     date == '01-24-2011'
        #     location == 's1'

将包含一个列表:
['a03'、'12-19-2011'、's2']
将其放入一个列表中可以方便地访问每个元素。因此,如果是这样的话,我将如何解释数据以回答问题您可以使用索引(即
行[0]
来访问列表中的第一项,即动物名称)如果不需要列表,只需省略line.split()位即可。好问题,一行一行的文件阅读行为有点奇怪你基本上说了与上面答案完全相同的事情,而其中一个只对第一个做了一个小的修改。当你查看上面答案的历史时,最初没有对文件进行关闭操作。那么,如果a-1更正确的话,为什么会是-1呢?这有点像是进入了一个新的话题,如何处理数据输出,但没什么好的。我认为我会尽力提供帮助,因为OP在对@AHuman的回答的评论中询问了解释数据的问题。在开始文本的注释中,它仍然不起作用,下面显示了builtins.FileNotFoundError:[Errno 2]没有这样的文件或目录:“animal data.txt”,尽管我很确定该文件已经存在。您是否从与“animal data.txt”文件相同的目录中运行脚本?如果没有,您必须指定文件的完整路径,或者使用
os
模块更改目录。
animal_names, dates, locations = [], [], []

with open('animal data.txt', 'r') as f:
    for line in f:
        animal_name, date, location = line.strip().split(':')
        animal_names.append(animal_name)
        dates.append(date)
        locations.append(location)

# Here, you have access to the three lists of data from the file
# For example:
#     animal_names[0] == 'a01'
#     dates[0] == '01-24-2011'
#     locations[0] == 's1'