【问题标题】:Python export only parts of list to CSVPython 仅将部分列表导出到 CSV
【发布时间】:2016-04-24 05:12:17
【问题描述】:

请你帮忙。 使用 Python 2.6.6。

我有一个名为“结果”的列表,例如:

# This is remark only: Type for `results`: <type 'list'>
1 86561198961563884 430cf63c640accf1c90ed2a9fe2ccce4
2 86561198160451905 d3fe1c990841552483955dfa81234338
3 86561198114921980 099c88e5c344233a388c0e558d3d88c8
4 86561198160858321 85cf9fa846e0f626c2490d12e9c9919e

当前正在使用代码写入文件“myOutput.csv”:

import csv
with open("myOutput.csv", "wb") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(results)

我希望这个在 csv 文件中:{Thus not the "first column" / rows[0]}

86561198961563884 430cf63c640accf1c90ed2a9fe2ccce4
86561198160451905 d3fe1c990841552483955dfa81234338
86561198114921980 099c88e5c344233a388c0e558d3d88c8
86561198160858321 85cf9fa846e0f626c2490d12e9c9919e

背景和原因。 已对列表进行了更改。
现在需要转到 CSV 进行 MySQL 导入。

谢谢,

【问题讨论】:

  • writer.writerows([line[1:] for line in results])?
  • 非常感谢。那行得通。请你告诉我我们称之为“动作、选项”的东西,这样我就可以去阅读和学习了。

标签: python python-2.7 csv export-to-csv


【解决方案1】:

Slice 关闭每行的第一项。

writer.writerows([line[1:] for line in results])

[1:] 表示从索引为 1 的元素开始的切片,它是第一项,一直到结尾。这构成了comprehension 的一部分,它为每一行执行此切片,创建一个新的list,并将其发送到writer.writerows

【讨论】:

    猜你喜欢
    • 2019-11-09
    • 2017-07-20
    • 2016-12-15
    • 2018-06-26
    • 1970-01-01
    • 2015-07-07
    • 2015-11-06
    • 2018-05-06
    • 1970-01-01
    相关资源
    最近更新 更多