rggod
rggod

Reputation: 629

what is the error with my python code?

i have this code

animal_names, dates, locations = [], [], []

filename=input("Enter name of file:")
if filename=="animallog1.txt":
    data=open('animallog1.txt','r')
    information=data.read()
    for line in information:
        animal_name, date, location = line.strip().split(':')
        animal_names.append(animal_name)
        dates.append(date)
        locations.append(location)   

    print(animal_names)
    print(dates)
    print(location)

i am trying to use the data in the txt file to print me the results i want the txt file contains the following :

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  

which is in the format animal_name:date:location

using the above i want to get

animal_names=[a01,a02, #till the very end,a03]

same for the rest of them(date,location), how can i fix my code so that is my result

I also need to use these lists the answer questions later

Upvotes: 1

Views: 76

Answers (1)

Hugh Bothwell
Hugh Bothwell

Reputation: 56694

Or

def main():
    fname = input("Enter name of file: ")
    with open(fname) as inf:
        names, dates, locations = zip(*[line.strip().split(':') for line in inf])

    print(names)
    print(dates)
    print(locations)

if __name__=="__main__":
    main()

Upvotes: 3

Related Questions