Earthling Person Earthling Person - 1 month ago 6
Python Question

Converting File Data to Lists

I have a file on sample employee data. The first line is the name, the second line is the salary, the third line is life insurance election (Y/N), the fourth line is health insurance election (PPOI, PPOF, None), and it repeats. A snippet of the file is below:

Joffrey Baratheon
190922
Y
PPOI
Gregor Clegane
47226
Y
PPOI
Khal Drogo
133594
N
PPOI
Hodor
162581
Y
PPOF
Cersei Lannister
163985
N
PPOI
Tyrion Lannister
109253
N
PPOF
Jorah Mormont
61078
Y
None
Jon Snow
123222
N
None


How can I take this file data and extract each data type (name, salary, life insurance, health insurance) into four separate lists? Currently, my code is creating a multidimensional list by employee, but I ultimately want four separate lists. My current code is below:

def fileread(text):
in_file = open(text, "r")
permlist = []
x = 1
templist = []
for line in in_file:
line = line.strip()
templist.append(line)
if x == 4:
permlist.append(templist)
templist = []
x = 1
else:
x+=1
return (permlist)
def main ():
EmpData = fileread("EmployeeData.txt")
index = 0
print (EmpData[index])

Answer

You could use 4 list comprehensions like so:

with open("file.txt",'r') as f:
    lines = f.readlines()

name_list = [lines[i].rstrip() for i in range(0,len(lines),4)]
salary_list = [lines[i].rstrip() for i in range(1,len(lines),4)]
life_ins_list = [lines[i].rstrip() for i in range(2,len(lines),4)]
health_ins_list = [lines[i].rstrip() for i in range(3,len(lines),4)]
Comments