Python 3.6
我正在尝试将设置值写入CSV,我得到了给定代码的以下输出。
import csv
class test_write:
@classmethod
def test_write1(cls):
fieldnames1 = ['first_name', 'last_name']
cls.write_a_test1(fieldnames=fieldnames1)
@classmethod
def write_a_test1(cls, fieldnames):
with open('/Users/Desktop/delete1.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
abc = cls.var1()
writer.writerow(abc)
print("Done writing")
@staticmethod
def var1():
d = ('my', 'name', 'is', 'hahaha')
c = set()
abc = {'first_name': c, 'last_name': d}
return abc
test_write.test_write1()
当我打开CSV文件时: 输出:
first_name last_name
set() ('my', 'name', 'is', 'hahaha')
如果它是空的,我不希望它在文件中打印set()。相反,我需要空白。变量“C”可能具有或不具有所依赖的值。我该如何处理。
答案 0 :(得分:0)
Dictwriter
期望键和值是字符串,因此在对象上调用str
。您应该使用的是:
d = ('my', 'name', 'is', 'hahaha')
c = set()
abc = {'first_name': ' '.join(c), 'last_name': ' '.join(d)}
return abc
文件的结果将是:
first_name,last_name
,my name is hahaha