pythonprintinglineexternal-data-source

Printing only specific words from .txt file - Python


Any help with the following question will be greatly appreciated.

I have the following .txt file named DOB:

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
Darren Christensen 21 January 1988
Shelia Harrison 28 July 1988
Ignacio James 12 September 1988
Jerry Keller 30 February 1988
Frankie Cobb 1 July 1988
Clayton Thomas 10 December 1988
Laura Reyes 9 November 1988
Danny Jensen 19 September 1988
Sabrina Garcia 20 October 1988
Winifred Wood 27 July 1988
Juan Kennedy 4 March 1988
Nina Beck 7 May 1988
Tanya Marshall 22 May 1988
Kelly Gardner 16 August 1988
Cristina Ortega 13 January 1988
Guy Carr 21 June 1988
Geneva Martinez 5 September 1988
Ricardo Howell 23 December 1988
Bernadette Rios 19 July 1988

I need to print all of the names and birth dates in the following format example:

Name:   
O Wright

Birthdate:
21 July 1988

My below code prints out the first character in caps as I need it to be, but how do I separate specific words thereafter and print them from a txt file?

The code I have so far is:

f = open('DOB.txt', 'r+')
for line in f:
    f = line[0] + ". "
    print(f)
g = open('DOB.txt')
for g in g.read().split():
    print(g)

Solution

  • Assuming each name is just a first and last name, no middle names etc. You can simply read each line of the file and split based on white space. The below will capture the first to fields in first and last, then the remaining fields in dob. Then we can just print the two lines using our variables. there is no need to loop through the file data twice.

    with open('test.txt') as my_file:
        for person in my_file:
            first, last, *dob = person.rstrip().split()
            print(f"Name: {first[0]}. {last}")
            print(f"Birthdate: {' '.join(dob)}")
    

    OUTPUT

    Name: O. Wright
    Birthdate: 21 July 1988
    Name: R. Holloway
    Birthdate: 13 September 1988
    Name: M. Figueroa
    Birthdate: 9 October 1988