【问题标题】:appending data frame to an existing csv files in python将数据框附加到python中的现有csv文件
【发布时间】:2020-12-26 07:51:11
【问题描述】:

我有几个数据框要附加到 python 中的 csv 文件。我正在使用以下代码来实现这一点,但还没有运气。

  import csv as writer
  import pandas as pd

def append_list_as_row(list_of_elem):
        # Open file in append mode
        with open('my_file.csv', 'a+', newline='') as write_obj:
            # Create a writer object from csv module
            csv_writer = writer(write_obj)
            # Add contents of list as last row in the csv file
            csv_writer.writerow(list_of_elem)
    append_list_as_row(new_data_frame)

抛出以下错误:

TypeError: 'module' object is not callable

谁能帮我解决这个问题?

【问题讨论】:

  • 为什么这个问题被标记为“dataframe”,你在任何地方都使用 pandas 吗?
  • 是的,我要附加到现有 csv 文件的数据是一个数据框。
  • 好的,list_of_elem 是数据帧列表吗?澄清这一点会很有帮助,因为变量命名不是很清楚:-)

标签: python dataframe csv append csv-write-stream


【解决方案1】:

我认为你忘记在csvwriter 初始化中使用 csv.writer。 试试这个

def append_list_as_row(list_of_elem):
# Open file in append mode
    with open('my_file.csv', 'a+', newline='') as write_obj:
        # Create a writer object from csv module
        csv_writer = writer(write_obj)
        # Add contents of list as last row in the csv file
        csv_writer.writerow(list_of_elem)
        csv_writer.close()
    append_list_as_row(new_data_frame)

还有一个问题,所有的帧都只有一行? 如果不是,你可以使用with。 像这样

for line in list_of_elem :
    csv_writer.writerow(line)

而且你忘记使用关闭文件。

【讨论】:

    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 2021-09-04
    • 2021-06-27
    • 2021-09-20
    • 2017-09-18
    • 1970-01-01
    • 2018-03-06
    • 2021-10-15
    相关资源
    最近更新 更多