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

3
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. 

我知道如何读取一行,但是由于这里有多行文本,我不确定如何读取每一行。

好问题,逐行读取文件的行为有些奇怪。 - trevorKirkby
4个回答

2

使用 for 循环。

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()

line 将包含一个列表:['a03','12-19-2011','s2'] - achedeuzot
将其放入列表中可以轻松访问每个元素。 - user2961646
如果是这种情况,我该如何解释数据以回答问题呢? - rggod
你可以使用索引(例如 line[0])访问列表中的第一个项目,即动物名称。 - user2961646
1
如果您不想要一个列表,只需省略line.split()这一部分。但实际上很少有这样做的情况。 - trevorKirkby

1

由于您了解此文件的格式,因此可以在其他答案上进一步缩短它:

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'

或者,如果您想要保留从文件中获取的信息的数据库以回答您的问题,可以执行以下操作:

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'

说到转移到新话题,我们来讨论一下如何处理数据输出,不过这仍然是一个好的话题。 - trevorKirkby
我想尝试提供帮助,因为OP在@AHuman的回答评论中询问了如何解释数据。 - Michael Herold
仍然关于打开文本的问题,它仍然无法工作,并且出现了以下错误builtins.FileNotFoundError: [Errno 2] No such file or directory: 'animal data.txt',尽管我非常确定该文件已经存在。 - rggod
你是在与 'animal data.txt' 文件相同的目录中运行脚本吗?如果不是,你必须指定文件的完整路径,或使用“os”模块更改目录。 - Michael Herold

0
你可以使用 with 语句来打开文件,在 open 失败的情况下。
>>> 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

-1

你忘记了关闭文件。最好使用with语句确保文件被关闭。

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

你基本上说的和上面的答案一模一样,而那个答案只是对第一个答案做了微小的修改。 - trevorKirkby
当您查看上面答案的历史记录时,最初文件上没有关闭操作。那么如果这样更正确,为什么会是-1呢? - Razer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接