-1

I'm having some trouble importing data from a txt file into an array. Here is the information in the txt file. It is an employee list with their names (don't mind my love of Star Wars), wage per hour, and hours worked.

Darth Vader
12.50
35
Princess Leia
13.50
40
Han Solo
14.25
10
Luke Skywalker
10.55
55

Here is my code:

text_file = open("/Applications/Python 3.8/Assignment1.txt", "r")
lines = text_file.readlines()
employees = []
counter = 1
for line in lines:
    print(line)
    employees.append(line[:-1])
    
print(employees)

How do I get it so every first line is a person's name, every second is their wage, and every third is their hours worked?

  • It's unclear what you're asking. What do you want this code to do? Please provide a sample output or data in the format / structure that you want. – user985366 Sep 13 '20 at 01:31
  • Read one line, use that to set the variable `name`, read the next line, convert it to `float`, and store that as the variable `wage`, read the next line, convert it to `float` (or to `int` if you only count whole hours) and store that as `hours`; then you can append the tuple `(name, wage, hours)` to your `employees` list. Instead of a `for line in lines` you might want to use a `while` instead. – Robby the Belgian Sep 13 '20 at 01:32
  • What you're describing is exactly the input file you shared? What problem are you trying to solve with the code? – Grismar Sep 13 '20 at 01:45

1 Answers1

0

Simplest is something like:

for line_no in range(0, len(lines), 3):
    name = lines[line_no]
    wage = float(lines[line_no + 1])
    hours = float(lines[line_no + 2])
    employee =  .. merge those into an employee however you want...
    employees.append(employee)

You might also want to look at this Stackoverflow answer for other ways of looking at a list in chunks.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22