How to change a .csv into lists and vice versa in python?

Question:

I need to split a .csv file:

user1,pass1,email1
user2,pass2,email2
user3,pass3,email3

into 3 lists that can be called upon and appended too seperately.

with open('userdata.csv', 'r') as f:
    userlist = [row[0] for row in csv.reader(f)]
    passlist = [row[1] for row in csv.reader(f)]
    emaillist = [row[2] for row in csv.reader(f)]
print(userlist)
print(passlist)
print(emaillist)

I need this code to return:

['user1', 'user2', 'user3']
['pass1', 'pass2', 'pass3']
['email1', 'email2', 'email3']

but this is what I get:

['user1', 'user2', 'user3']
[]
[]

Once this works, I also need a way to write it back as a .csv that will be in the exact format it was when I called it but with added information so it can be called again whenever needed.

Asked By: hunt-g

||

Answers:

You’re trying to consume the csv file three times by calling csv.reader(f) repeatedly.

You can instead store the rows in a temporary list and get columns from that list.

with open('userdata.csv', 'r') as f:
    rows = list(csv.reader(f))
    userlist = [row[0] for row in rows]
    passlist = [row[1] for row in rows]
    emaillist = [row[2] for row in rows]

A more elegant way of picking out columns from rows would be through the use of zip:

with open('userdata.csv', 'r') as f:
    userlist, passlist, emaillist = zip(*(row for row in csv.reader(f)))

For writing the csv file, zip can be used in the other direction, to convert columns back to rows:

with open('output.csv', 'w', newline='') as f:
    csv.writer(f).writerows(zip(userlist, passlist, emaillist))
Answered By: Tugrul Ates
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.