Converting File Data to Lists
<p>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:</p>

<pre><code>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
</code></pre>

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

<pre><code>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])
</code></pre>

<p>You can use <code>islice</code> from the <code>itertools</code> library. It will allow you to iterate over batches of 4 lines at a time.</p>

<pre><code>from itertools import islice
EmpData = []
headers = ['name', 'salary', 'life insurance', 'health insurance']
record = {}
counter = 1
with open('data.txt', 'r') as infile:
    while counter&gt;0:
        lines_gen = islice(infile, 4)
        counter = 0
        hasLines = False;
        for line in lines_gen:
            record[headers[counter]] = line.strip()
            counter += 1
        EmpData.append(record)
index = 0
print (EmpData[index])
</code></pre>

<p>As someone has complained about scholastic dishonesty violations in this post, I would make to clear that is a simplified version of a production code snippet that was inspired by this SO answer: <a href="http://stackoverflow.com/questions/5832856/how-to-read-file-n-lines-at-a-time-in-python">How to read file N lines at a time in Python?</a>. </p>

python list python-3.x