我需要分割一个.csv文件:
user1,pass1,email1
user2,pass2,email2
user3,pass3,email3
分为3个可以单独调用和附加的列表。
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)
我需要以下代码才能返回:
['user1', 'user2', 'user3']
['pass1', 'pass2', 'pass3']
['email1, 'email2', 'email3']
但这就是我得到的:
['user1', 'user2', 'user3']
[]
[]
一旦成功,我还需要一种将其写为.csv的方式,其格式与我调用时的格式完全相同,但要添加信息,以便可以在需要时再次调用它。
答案 0 :(得分:2)
您要通过重复调用csv.reader(f)
来尝试使用csv文件三次。
您可以将行存储在临时列表中,并从该列表中获取列。
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]
从行中选择列的一种更优雅的方法是使用zip
:
with open('userdata.csv', 'r') as f:
userlist, passlist, emaillist = zip(*(row for row in csv.reader(f)))
要写入csv文件,可以将zip
用于另一个方向,以将列转换回行:
with open('output.csv', 'w', newline='') as f:
csv.writer(f).writerows(zip(userlist, passlist, emaillist))