【问题标题】:How to write data into a CSV file using python?如何使用 python 将数据写入 CSV 文件?
【发布时间】:2014-10-17 07:00:40
【问题描述】:

我正在尝试将以下数据写入 csv 文件。数据是使用详细信息

name1-surname1-place1

name2-surname2-place2

name3-surname3-place3

name4-surname4-place4

我希望输出在 CSV 文件中,在单独的行中一个在另一个之下。

我已经写了下面的代码

reader = csv.reader(文件)

op = open(path+"op.CSV", "wb")

String=list[0] + "-" + list[1] + "-" + list[2] + "-" + list[4]

 op.writer(String)

请帮忙。

提前致谢。

-KD

【问题讨论】:

  • 如果是 CSV 文件,你不应该在里面放逗号吗?
  • CSV 可以并且确实有许多不同的字符用作分隔符。例如,在某些国家/地区,实际是小数的符号。 Source
  • 嗯!每天学些新东西! :)

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


【解决方案1】:

如果我很好地理解了您的问题,那么您正在寻找这个:

>>> import csv
>>> employees = [
...     'name1-surname1-place1',
...     'name2-surname2-place2',
...     'name3-surname3-place3',
...     'name4-surname4-place4',
... ]
>>> with open('out.csv', 'w') as out:
...     writer = csv.writer(out)
...     for e in employees:
...         writer.writerow(e.split("-"))
... 
>>> 
>>> 
host:~$ head out.csv 
name1,surname1,place1
name2,surname2,place2
name3,surname3,place3
name4,surname4,place4

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 2016-02-10
    • 2018-03-22
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多