【问题标题】:write key and values in csv file using for loop -- python使用for循环在csv文件中写入键和值——python
【发布时间】:2019-01-25 18:16:45
【问题描述】:

我是python新手,请帮我解决这个问题。

我的代码如下:

if div == 0 or div == 1 or div == 2:
     print (' A ', 'sometext')

elif div == 5 or div == 6:
     print (' B ', 'some')

elif div == 3 or div == 4:
     print (' C ', 'text')

我想将数据插入 csv 而不是打印

像这样:

A,B,C
sometext,some,text
xhbasj,bjascn,bashc
bhhashc,bashjc,bcsahbch
cvashcj,bcashc,bcasc

这里的 A、B、C 就像键。

我尝试了很多选项,但没有一个有效,请帮我解决这个问题

我试过了

with open('trashData.csv', 'w', newline='') as fp:
    a = csv.writer(fp, delimiter=',')
    if div == 0 or div == 1 or div == 2:
       data = [['A'],['sometext']]
       a.writerows(data)

【问题讨论】:

  • 你能展示一些你试过的代码吗?
  • 是的,我做到了@argo

标签: python list csv


【解决方案1】:

打开文件进行写入并获取 csv 写入器:

import csv
with open('my_file.csv', mode='w') as f:
    csv_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

然后给你写上键:

csv_writer.writerow(['A', 'B', 'C'])

然后做你的循环

for ...

然后在里面写下你的代码:

if div == 0 or div == 1 or div == 2:
      csv_writer.writerow(['sometext', 'some', 'text']
...

示例:

import csv

with open('my_file.csv', mode='w') as f:
    csv_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['A', 'B', 'C'])
    for i in range(10):
        csv_writer.writerow(['i', i, 10-i])

将写入以下文件:

A,B,C
i,0,10
i,1,9
i,2,8
i,3,7
i,4,6
i,5,5
i,6,4
i,7,3
i,8,2
i,9,1

【讨论】:

  • 你不认为 csv_writer.writerow 会覆盖 csv 值并且看起来像:
  • A,B,C i,9,1 @Er​​an
  • @MukundS,writerow 不会覆盖之前的行,它会添加一个。你可以自己试试这段代码看看(这就是我添加一个完整的工作示例的原因)
【解决方案2】:

这段代码对我有用,参考:Python: Writing a dictionary to a csv file with one line for every 'key: value'

import csv

dictionary = {'A':'Text', 'B':'Sometext'}

f = open('dictionary.csv', 'w+')
writer = csv.writer(f)
for k,v in dictionary.items():
    writer.writerow([k,v])

【讨论】:

    猜你喜欢
    • 2018-01-12
    • 2018-03-14
    • 1970-01-01
    • 2015-08-12
    • 2018-01-19
    • 2017-03-25
    • 2013-03-21
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多