Jeandre Verster
Jeandre Verster

Reputation: 15

Create different lists in Python from a text file

So I have a text file called DOB that contains names and birthdates, and the .txt file is saved as follows (I'm only including the first few lines as there are quite a few of them:

Orville Wright 21 July 1988

Rogelio Holloway 13 September 1988

Marjorie Figueroa 9 October 1988

Debra Garner 7 February 1988

Tiffany Peters 25 July 1988

Hugh Foster 2 June 1988

What I would like to do is create a list of the names, and another list containing the birth dates. However, I don't know how to extract only a specific word/s in a line and append them to the list. Would anybody be able to help me in understanding how to do that?

Upvotes: 0

Views: 224

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195438

This script assumes, that persons can have more than 2 names and the date consists of three strings (day, month and year):

names, dates = [], []
with open('your_text_file.txt', 'r') as f_in:
    for line in map(str.strip, f_in):
        if not line:    # skip empty lines
            continue
        tmp = line.split()
        
        names.append(' '.join(tmp[:-3]))
        dates.append(' '.join(tmp[-3:]))

print(names)
print(dates)

Prints:

['Orville Wright', 'Rogelio Holloway', 'Marjorie Figueroa', 'Debra Garner', 'Tiffany Peters', 'Hugh Foster']
['21 July 1988', '13 September 1988', '9 October 1988', '7 February 1988', '25 July 1988', '2 June 1988']

Upvotes: 1

ILoID
ILoID

Reputation: 93

You could do this by using either the String .split(' ') method and accessing each value how you would access a list. Another great way to store this kind of information would be using the CVS module in python. You can read about its usage here. Hope I could help!

Upvotes: 0

Related Questions