如何在python中将.csv转换为列表,反之亦然?

fhity93d  于 2023-01-28  发布在  Python
关注(0)|答案(1)|浏览(290)

我需要拆分.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,将在确切的格式,它是当我调用它,但添加信息,使它可以再次调用时,需要的。

vu8f3i0k

vu8f3i0k1#

您尝试通过重复调用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))

相关问题