简体   繁体   English

python csv 写入两列

[英]python csv writing into two columns

I am trying to write the output of a python calculation to csv in two columns.我正在尝试将 python 计算的 output 写入两列中的 csv。 I tried the following to achieve this, but failed.我尝试了以下方法来实现这一点,但失败了。

import csv

with open('data.csv', 'ab') as f:
    writer = csv.writer(f)
    for row in [level, variable]:
        writer.writerow([row])

the print output of print(level, variable) is as follows, print(level, variable) 的打印 output 如下,

(1, 0)
(2, 0)
---
---
---
(33, 8)
(34, 7)
(35, 6)
(1, 0)
(2, 0)
---
---
---
(33, 10)
(34, 1)
(35, 2)

How can I write this print output in to two columns of csv file?如何将此打印 output 写入两列 csv 文件? Can anyone give a answer?谁能给出答案? Thanks in advance!提前致谢!

A csv is literally just a file with C omma S eperated V alues. csv 实际上只是一个包含C omma S eperated值的文件。 So technically:所以从技术上讲:

f = open("whatever.csv")
[for loop]
    f.write(f"{value1}, {value2}\n")
f.close()

should do the trick.应该做的伎俩。 Where value1 and value2 are the name of your 2 values.其中 value1 和 value2 是您的 2 个值的名称。

Can you try this.你能试试这个吗?

  import csv
    
    with open('data.csv', 'w') as f:
        writer = csv.writer(f)
        writer.writerows(zip(level, variable))

you can also try你也可以试试

f=open(data.csv,'w')
for i,j in zip(level,variable):
    f.write(str(i)+","+str(j))
f.close()

Just an idea, but you should try to:只是一个想法,但你应该尝试:

  • Build a list建立一个清单
  • Put in your list your tuples (python identifies tuples with parenthesis)把你的元组放在你的列表中(python 用括号识别元组)
  • Send your list of tuples in your csv在您的 csv 中发送您的元组列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM