【问题标题】:How can i write to a csv file? [closed]如何写入 csv 文件? [关闭]
【发布时间】:2016-09-05 07:38:54
【问题描述】:

我需要更新库存清单,我该如何以这种方式写入 CSV 文件。请问您如何写入 CSV 文件?我试过搜索这个,但没有什么能真正解释他们为什么这样做。

【问题讨论】:

标签: python csv


【解决方案1】:

https://docs.python.org/2/library/csv.html

import csv
with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

代码说明

  1. 导入 csv 类
  2. 打开文件“some.csv”并为其命名,我们可以使用它来引用它
  3. “wb”为文件模式,写入二进制。如果我们只想阅读,这将是“rb”。
  4. 我们使用 csv 类函数 writer 创建一个新的 writer 对象,并将其传递到我们的文件中
  5. 我们在 writer 对象上调用 write rows,并将其传递到任何可迭代对象中

一个可迭代对象可以是一个简单的列表,例如

my_iterable = ["Printed to line 1", "Printed to line 2"]

【讨论】:

    【解决方案2】:

    正如您所说,您有一个股票“列表”,我更愿意使用 pandas 写入 .csv。考虑到您有一个名为“stock_list”的股票列表

    stock_list = [list of elements]
    
    import pandas as pd
    df = pd.DataFrame(stock_list, columns=["whatever name you want to give"])
    
    df.to_csv("path to which you need to save", index=True/False (Depends on whether you need the index or not))
    

    【讨论】:

      猜你喜欢
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-12-21
      • 2018-03-19
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 2020-10-22
      相关资源
      最近更新 更多