Read text file into dictionary to be used later for adding/modifying/deleting
Question: Let me preface by saying I'm not 100% sure if using a dictionary is the best
course of action for this task but that is what I believe I need to use to
accomplish this.

I have a .txt file that is formatted like this:

    
    
    first_name last_name rate hours
    first_name last_name rate hours
    first_name last_name rate hours
    first_name last_name rate hours
    

There is a single space between each item. Each line represents a person.

For my program I need to be able to:

  * print out all the people at once
  * be able to search for a person by first or last name and print out their information 
  * modify a person (first name, last name, hours, rate)
  * delete a person (all their information)

When it gets printed I **_DO NOT_** need to see the [rate] and [hours] but
[gross pay] instead (gross pay = rate * hours).

I am fairly new to file processing with python so my first attempt at this was
just to read every line from the file and print it out on the screen, but I
came across the problem of being able to display [gross pay].

    
    
    # 'print_emp', display only a single employee's data chosen by the user displayed as
    # firstname, lastname, grosspay (on one line of output)
    def print_emp():
        menu_name = ' '*int(OFFSET/2) + "EMPLOYEE LOOKUP"
        dotted = (OFFSET+len(menu_name))*'-'
    
        try:
            with open('employees.txt') as file:
                print('{} \n{} \n{}'.format(dotted, menu_name, dotted))
                emp_name = input("Employee Name: ")
                print('{0:20} {1:20} {2}'.format("First Name", "Last Name", "Gross Pay"))
                for line in file:
                    if emp_name in line:
                        print (line.strip())
    
                    #print("\nEmployee", emp_name, "does not exist. Try again.\n")
                    #break
        except FileNotFoundError:
            print("Error: File not found.")
    
    
    # 'print_all_emp', display all employee data in format firstname, lastname,
    # grosspay (on one line of output per employee)
    def print_all_emps():
        menu_name = ' '*int(OFFSET/2) + "EMPLOYEE LIST"
        dotted = (OFFSET+len(menu_name))*'-'
    
        try:
            with open('employees.txt', 'r') as file:
                print('{} \n{} \n{}'.format(dotted, menu_name, dotted))
                print('{0:20} {1:20} {2}'.format("First Name", "Last Name", "Gross Pay"))
                for line in file:
                    print(line.strip())
                print(dotted)
        except FileNotFoundError:
            print("Error: File not found.")
    

I am not sure how I go about reading my .txt file into a dictionary (if that's
what I need to do) where I assign a key to each person that includes their
first name, last name, rate, and hours and then multiplying the rate * hours
to create the gross pay and then displaying that gross pay.

I will be creating three more functions where I can add, delete, and modify
the people in the .txt file.

**EDIT :**

I believe what I am going for as an end program looks something like this:

<https://en.wikibooks.org/wiki/Non-
Programmer%27s_Tutorial_for_Python_3/File_IO>

But without the load and save functions...


Answer: Presuming you have space delimited data, you can just use the csv library.

    
    
    import csv
    
    labels = ['first_name', 'last_name', 'rate', 'hours']
    data = csv.DictReader(open('./test.txt'), delimiter=' ', fieldnames=labels)
    
    result = []
    
    for row in data:
      result.append(row)
    
    print result
    

You will wind up with an array of dictionaries that each have the labels as
key names.

