0

I have a .txt file (with several lines of data) in the following format: last name,first name,rate,hours,gross pay

I need to create a program that will open that file (I think I have this part, below) and display each line of the file as a comma-delimited. What should I use? A list or a dictionary?

I know that dictionaries can only support two items, but these lines have 5 fields, would a list work better? And what would be the best way to go about the code? Thank you in advance!

def main():
    f = open("payroll.txt", "r")
Jonathan Callen
  • 11,301
  • 2
  • 23
  • 44
Julinha
  • 13
  • 1
  • Dictionaries can store a lot more than 2 elements... You would probably use an array of dictionaries, or an array of objects if that would actually help your program be easier to understand. – ktb Jun 01 '17 at 04:37
  • Please provide a few (two or three) lines of example input, and the corresponding output that you'd like to produce – Jon Kiparsky Jun 01 '17 at 04:41

1 Answers1

0

Your input format is not clear. If your source data file contains comma-separated values, you probably want to use the csv library.

Simple example:

import csv
f = open ("payroll.txt", "r")
reader = csv.reader(f)
for line in reader:
    # each line is a list of values, proceed from here

alternatively, you can use the DictReader:

import csv
f = open ("payroll.txt", "r")
reader = csv.DictReader(f)
for line in reader:
    # each line is a dictionary of key:val pairs, keys taken from the 
    # header row

If your input format is not comma-separated, you'll need to give an example of what exactly you're reading, and how you want to display it.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
  • I think I got it. Thank you! 6 def main(): 7 f = open("payroll.txt", "r") 8 lis = {} 9 for line in f: 10 employee = line.rstrip().split(",") 11 if len(employee) > 1: 12 emp = {} 13 print(employee) 14 emp["Last Name"]=employee[0] 15 emp["First Name"]=employee[1] 16 emp["Rate"]=float(employee[2]) 17 emp["Hours"]=float(employee[3]) 18 emp["Gross Pay"]=float(employee[4]) 19 lis[len(lis)]=emp 20 print(lis) 21 22 main() – Julinha Jun 05 '17 at 23:15