python - 按行和列写入 csv

标签 python list csv dictionary writer

我已经快要完成了,但无法解决这个问题。 我正在写入 csv,我的代码不断给我这个输出。

 dict,a,b,c,d
 ,,,,
 list,1,2,3,4

我希望它如下:

 dict, list
 a,1
 b,2
 c,3
 d,4

代码是:

    ##Opening my dictionary .cvs file
    with open('some_file.csv', mode='r') as infile:
        reader = csv.reader(infile,)
        DICT = {rows[0]:rows[1] for rows in reader if len(rows) == 2}

    ##Opening my enquiry list .cvs file
    datafile = open(self.filename, 'r')
    datareader = csv.reader(datafile)
    n1 = []
    for row in datareader:
        n1.append(row)

        n = list(itertools.chain(*n1))

    headings = ['dict', 'list']

    ##Writing to .cvs file       
    with open(asksaveasfilename(), 'w') as fp:
        a = csv.writer(fp)
        # write row of header names
        a.writerow(n)

        # build up a list of the values in DICT corresponding to the keys in n
        values = []
        for name in n:
            if name in DICT:
                values.append(DICT[name])
            else:
                values.append("Not Available")

        # now write them out
        a.writerow(values)

我尝试使用writerows,但这打印的数据也错误

d,i,c,t
a
b
c
d
l,i,s,t
1
2
3
4
<小时/>

解决方案:

    for nameValueTuple in zip(n,values):
    a.writerow(nameValueTuple)

成功了

最佳答案

直接写入数据

import csv

DICT = {a:a*a for a in [1,2,3,4,5]}
n = [2, 5, 99, 3]

headings = ['dict', 'list']

##Writing to .cvs file       
with open("try.csv", 'w') as fp:
  a = csv.writer(fp)
  a.writerow(headings)
  for name in n:
    if name in DICT:
       a.writerow([name, DICT[name]])
    else:
       a.writerow([name, "Not Available"])

这将导致 try.csv 包含:

dict,list
2,4
5,25
99,Not Available
3,9

先进行处理,然后写入处理后的行:

您还可以一次进行处理并编写所有内容:

import csv

DICT = {a:a*a for a in [1,2,3,4,5,6]}
ns = [2,3,99,5]

headings = ['dict', 'list']

ns_squared = [DICT[name] if name in DICT else "NOT_FOUND" for name in names]

print(ns_squared) #=> [4, 9, 'NOT_FOUND', 25]

rows = zip(ns,ns_squared)

with open("try.csv", 'w') as fp:
  a = csv.writer(fp)
  a.writerow(headings)
  a.writerows(rows)

这将导致:

dict,list
2,4
3,9
99,NOT_FOUND
5,25

使用 zip 将列转换为行

如果您将列作为列表,则可以使用 zip() 内置函数将它们转换为行。例如:

>>> column1 = ["value", 1, 2, 3, 4]
>>> column2 = ["square", 2, 4, 9, 16]
>>> zip(column1,column2)
[('value', 'square'), (1, 2), (2, 4), (3, 9), (4, 16)]

关于python - 按行和列写入 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17293455/

相关文章:

python - SE_SYSTEMTIME_NAME 权限不存在

python - 我有一个包含字符串和 float 的列表,如何按降序对数字进行排序并将列表打印到标准输出

Python:我创建了 2 个列表,对其中之一进行排序,它们都得到排序

python - Scipy Curve_fit : Why is my fitting so poor and how to improve it?

Python 大型多列表高效查询

java - 当我删除一个项目时,回收站查看列表修改所有项目

json - 如何转义 JSON 字符串以进行 CSV 解析?

python - 如何在标题前使用配置行写入 csv 数据框

python - 如何跳过行直到在txt文件中找到 'keyword'并将其余部分保存为csv? Python

python - 无法将库升级到 Google Colab 上的特定版本(scipy 版本 1.8.0)