Read from text file and assign data to new variable
Question: Python 3 program allows people to choose from list of employee names. Data
held on text file look like this: **('larry', 3, 100)** (being the persons
name, weeks worked and payment)

I need a way to assign each part of the text file to a new variable, so that
the user can enter a new amount of weeks and the program calculates the new
payment.

Below is my code and attempt at figuring it out.

    
    
    import os
    choices = [f for f in os.listdir(os.curdir) if f.endswith(".txt")]
    print (choices)
    emp_choice = input("choose an employee:")
    
    file = open(emp_choice + ".txt")
    
    data = file.readlines()
    name = data[0]
    weeks_worked = data[1]
    weekly_payment= data[2]
    
    new_weeks = int(input ("Enter new number of weeks"))
    new_payment = new_weeks * weekly_payment
    print (name + "will now be paid" + str(new_payment))
    


Answer: currently you are assigning the first three lines form the file to `name`,
`weeks_worked` and `weekly_payment`. but what you want (i think) is to
separate a single line, formatted as `('larry', 3, 100)` (does each file have
only one line?).

so you probably want code like:

    
    
    from re import compile
    
    # your code to choose file
    
    line_format = compile(r"\s*\(\s*'([^']*)'\s*,\s*(\d+)\s*,\s*(\d+)\s*\)")
    file = open(emp_choice + ".txt")
    line = file.readline()   # read the first line only
    match = line_format.match(line)
    if match:
        name, weeks_worked, weekly_payment = match.groups()
    else:
        raise Exception('Could not match %s' % line)
    
    # your code to update information
    

the regular expression looks complicated, but is really quite simple:

    
    
    \(...\)  matches the parentheses in the line
    \s*      matches optional spaces (it's not clear to me if you have spaces or not
             in various places between words, so this matches just in case)
    \d+      matches a number (1 or more digits)
    [^']*    matches anything except a quote (so matches the name)
    (...)    (without the \ backslashes) indicates a group that you want to read 
             afterwards by calling .groups()
    

and these are built from simpler parts (like `*` and `+` and `\d`) which are
described at <http://docs.python.org/2/library/re.html>

if you want to repeat this for many lines, you probably want something like:

    
    
    name, weeks_worked, weekly_payment = [], [], []
    for line in file.readlines():
        match = line_format.match(line)
        if match:
            name.append(match.group(1))
            weeks_worked.append(match.group(2))
            weekly_payment.append(match.group(3))
        else:
            raise ...
    

