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

时间:2013-11-23 23:21:12

标签: python

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文件,where animal name : date : location 所以我必须阅读这个txt文件来回答问题。

所以到目前为止我已经

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

我知道怎么读一行,但是这里因为有多行我不知道如何读取txt中的每一行。

4 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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'

答案 2 :(得分: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

答案 3 :(得分:-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