Python:从两个列表中制作一个csv

时间:2018-08-27 15:50:41

标签: python python-3.x list csv

让我们假设我有两个列表:

users = [ user1, user2, user3, ...]
codes = [ code1, code2, code3, ...]

我想创建一个csv,在其中我为每个用户分配一个代码,如下所示:

users, codes
user1, code1
user2, code2 

我已经尝试了好几天,但找不到解决方案。我试图扩展该列表,但是它不能按预期的方式工作。谢谢

5 个答案:

答案 0 :(得分:2)

zipcsv模块一起使用

例如:

import csv    

users = [ 'user1', 'user2', 'user3']
codes = [ 'code1', 'code2', 'code3']

with open(filename, "w") as infile:
    writer = csv.writer(infile)
    writer.writerow(["users", "codes"])    #Write Header
    for i in zip(users, codes):
        writer.writerow(i)                 #Write Content

答案 1 :(得分:0)

这是很常见的事情。如@Denziloe所指出的,查看模块pandas或使用csv.writer

import csv
with open("my_csv", "w") as f:
   writer = csv.writer(f)
   writer.writerow(["user", "code"])
   for a, b in zip(users, codes):
       writer.writerow([a, b])

答案 2 :(得分:0)

您可以使用pandas将此信息存储在数据框中,然后使用df.to_csv()

import pandas as pd

users = ['user1', 'user2', 'user3']
codes = ['code1', 'code2', 'code3']

pairs = {'Users': users, 'Codes': codes}

df = pd.DataFrame.from_dict(pairs)

df.to_csv('mycsv.csv')

答案 3 :(得分:0)

如果使用此代码,则无需导入:

users = [ 'user1', 'user2', 'user3']
codes = [ 'code1', 'code2', 'code3']

with open('solution.csv', 'w') as f:
    f.write('users,codes\n')
    for user, code in zip(users, codes):
        f.write('{},{}\n'.format(user, code))

它将为您创建一个像这样的文件:

users,codes
user1,code1
user2,code2
user3,code3

答案 4 :(得分:0)

为我工作(来自https://docs.python.org/2/library/csv.html

        users = ['user1', 'user2', 'user3']
        codes = ['code1', 'code2', 'code3']
        with open('output.csv', 'wb') as csvFile:
            fieldnames = ['USER', 'CODE']
            output = csv.DictWriter(csvFile, fieldnames=fieldnames)
            output.writeheader()
            for index, user in enumerate(users):
                output.writerow({'USER': user, 'CODE': codes[index]})

我知道了

enter image description here