【问题标题】:Write multiple values in a csv cell without brackets in python在python中不带括号的csv单元格中写入多个值
【发布时间】:2016-09-06 19:28:35
【问题描述】:

我有一个对象列表。每个对象都有不同的属性。 其中之一是列表 我想将这些对象导出到一个 csv 文件,看起来像

a, "1,2,3"
b,"1,2,3"

这样 csv 在 Excel 程序中是可读的

我的代码如下所示:

final_list = []
for a in list:
        first_value = a.first_value
        list2 = []
        for b in a.list:
            list2.append(b)

        final_list.append(first_value)
        final_list.append(list2)
with open('file' ) as f:
        writer = csv.writer(f)
        writer.writerows(final_list)
    pass           

这会导致这个 csv 行带有我不想要的括号和引号

1, "['1','3','4']"
2,"['1','2','3']"

我需要每行 2 个值:a1,2,3 作为字符串

【问题讨论】:

  • 我想要 2 个值 a 和 1,2,3 作为字符串
  • 最好编辑您的问题,而不是在下面发表评论。评论是一次性的。问题是进一步读者的真正资产。这一次,我用你的评论为你编辑了它,这给了你一票:)

标签: python excel csv


【解决方案1】:

如果你这样做:

    final_list.append(first_value)
    final_list.append(list2)

您创建一个包含值和列表的行。

csv 模块在写入时执行str 转换,这说明您在 python 中调试时会看到打印的字符串。

改为:

    final_list.append(a.first_value)  # string
    final_list.append(",".join(a.list))  # composes a coma separated string with the contents of a.list

结果:

a,"1,2,3"

(引号保护逗号,使其被视为单个单元格)

【讨论】:

  • 您可能希望确保列表中的所有值都没有逗号,以便您可以按照编写它们的方式读回这些值。在附加之前类似于assert all(',' not in value for value in list2)
  • 还是在csv行写一个csv行?
猜你喜欢
  • 2020-10-15
  • 2021-01-03
  • 2011-03-29
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多