You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python列表转为指定格式字符串并正确写入CSV文件?

Python列表格式转换及CSV写入问题解决

初始需求

我有如下Python列表:

my_list = ['Food']

需要将其转换为如下格式的字符串:

"["food"]"

问题更新:CSV写入异常

尝试将内容写入CSV文件时,得到了空字符串,使用的代码如下:

with open("food.csv", "x", encoding="utf-8") as file:
    wr = csv.writer(file)
    wr.writerow(["Food", "Id",])
    wr.writerow(str(my_list))
    wr.writerow('1')

最终解决方法

问题已解决!正确代码如下:

with open("languages_books.csv", "x", encoding="utf-8") as file:
    wr = csv.writer(file)
    wr.writerow(["Food", "Id",])

    wr.writerows([ [[my_list]], ['Id'] ])

内容的提问来源于stack exchange,提问作者Joiny Support

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 01:54:22