我正在从一个数据集合中编写一个新的CSV文件,稍后我想将其导入SQL数据库。
数据应该以JSON格式存储在“size”和“colors”列中。
如何将列括在单引号中,将括号中的数据括在双引号中?
with open("export.csv", "w", newline="") as csvfile:
# Create a CSV writer using the field/column names
writer = csv.DictWriter(
csvfile,
fieldnames=csv_fields,
)
# Write the header row (column names)
writer.writeheader()
for key in dict_products:
print(dict_products[key])
writer.writerow(dict_products[key])
这就是现在正在创造的。
id,prodcategory_id,name,featured,image_1,image_2,image_3,image_4,colors,sizes,article_number,price,manufacturer_id
NULL,521,,0,521010000-1.jpg,,,,['1'],"['39', '41', '42', '43', '44', '45', '46']",521010000,6990,582
NULL,115,Women Court Sho,0,115130000-1.jpg,,,,['13'],"['36', '37', '38', '39', '40', '41']",115130000,4990,32
应该是这样的
id,prodcategory_id,name,featured,image_1,image_2,image_3,image_4,colors,sizes,article_number,price,manufacturer_id
NULL,521,,0,521010000-1.jpg,,,,["1"],'["39", "41", "42", "43", "44", "45", "46"]',521010000,6990,582
NULL,115,Women Court Sho,0,115130000-1.jpg,,,,["13"],'["36", "37", "38", "39", "40", "41"]',115130000,4990,32
1条答案
按热度按时间kxkpmulp1#
对我来说,它看起来像
dict_products
是一个字典,有一个键和你想要的csv行作为值。colors
和sizes
键看起来像列表。要获得引用的结果,您需要对每个值使用json.dumps
。然后在写csv时,指定单引号('
)作为引号字符。https://onlinegdb.com/PBKLPNoar