【问题标题】:Unable to append a row to csv in Python无法在 Python 中将行附加到 csv
【发布时间】:2020-11-07 07:01:51
【问题描述】:

我正在使用以下函数将行附加到现有的 csv 文件。当我在我的代码中调用此函数时,它没有给我任何错误,但它没有将任何内容附加到文件中。几天前,具有相同代码的相同功能似乎工作得非常好。重新启动 Anaconda/Jupyter Notebook 时是否必须执行任何特定步骤才能使此功能正常工作?

def append_list(file_name, list_of_elem):
# Open file in append mode
with open(file_name, '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)
    # List of strings

非常感谢

【问题讨论】:

  • 请使您的代码有效(append_list 函数内的缩进,with ... 行应缩进)

标签: python csv append jupyter write


【解决方案1】:

上下文管理器存在缩进问题。试试这个:

def append_list(file_name, list_of_elem):
     with open(file_name, 'a+', newline='') as write_obj:
         write_obj.writestr(list_of_elem)

【讨论】:

  • 对不起,我更正了缩进,但它仍然不起作用
【解决方案2】:

试试这个。它会起作用的。

import csv  
 
def append_list(file_name, list_of_elem):
with open(file_name, 'a', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(list_of_elem)

【讨论】:

    猜你喜欢
    • 2020-02-17
    • 2012-09-26
    • 2019-07-11
    • 1970-01-01
    • 2019-03-26
    • 2013-11-14
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多