Manipulating data from text file - Python 2.7

122 Views Asked by At

I need help importing data like this from a text file:

Orville Wright 21 July 1988

Rogelio Holloway 13 September 1988

Marjorie Figueroa 9 October 1988

and display it on the python shell like this:

Name

  1. O. Wright
  2. R. Holloway
  3. M. Figueroa

Birth date

  1. 21 July 1988
  2. 13 September 1988
  3. 9 October 1988
1

There are 1 best solutions below

0
On

Read lines of files into a list In Python, how do I read a file line-by-line into a list?

Enumeration https://docs.python.org/2.3/whatsnew/section-enumerate.html

with open('filename') as f:
  lines = f.readlines()  # see above link
  names = []  # list of 2-element lists to store names
  timestamps = []  # list of 3-element lists to store timestamps as day/month/year 

  # preprocess 
  for line in lines:
    a = line.split(" ")  # the delimiter you use appears to be a space
    names.append(a[:2])  # everything up to and excluding third item after split
    timestamps.append(a[2:])  # everything else

  # output
  print("some header here") # put whatever you want here
  for i, name in enumerate(names):  # see enumeration reference
    # you could add a length check on name[0] in case first name is blank
    print("{}. {}. {}".format(str(i+1), name[0][0], name[1]))  
  print("another header here") # again use whatever header you want here
  for i, timestamp in enumerate(timestamps):
    print("{}. {}".format(str(i+1), " ".join(timestamp))