我有两个参数,例如filename
和time
,我想将它们写在csv
文件的列中。这两个参数位于for-loop
中,因此它们的值在每次迭代中都会更改。
我当前的python代码是下面的代码,但生成的csv不是我想要的:
import csv
import os
with open("txt/scalable_decoding_time.csv", "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
filename = ["one","two", "three"]
time = ["1","2", "3"]
zipped_lists = zip(filename,time)
for row in zipped_lists:
print row
writer.writerow(row)
我的csv
文件必须如下所示。 ,
必须是分隔符。所以我必须得到两列。
one, 1
two, 2
three, 3
我的csv
文件现在如下图所示。数据存储在一列中。
你知道如何解决这个问题吗?
答案 0 :(得分:2)
嗯,这里的问题是,您使用的是writerows
而不是writerow
import csv
import os
with open("scalable_decoding_time.csv", "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
level_counter = 0
max_levels = 3
filename = ["one","two", "three"]
time = ["1","2", "3"]
while level_counter < max_levels:
writer.writerow((filename[level_counter], time[level_counter]))
level_counter = level_counter +1
这给了我结果:
one,1
two,2
three,3
输出:
答案 1 :(得分:0)
这是另一种解决方案
将以下代码放入我们将调用sc-123.py
filename = ["one","two", "three"]
time = ["1","2", "3"]
for a,b in zip(filename,time):
print('{}{}{}'.format(a,',',b))
一旦脚本准备就绪,就像那样运行
python2 sc-123.py > scalable_decoding_time.csv
您将按照您希望的方式格式化结果
one,1
two,2
three,3