首页 > 解决方案 > 无法在 Python 中将行附加到 csv

问题描述

我正在使用以下函数将一行附加到现有的 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

非常感谢

标签: pythoncsvappendjupyterwrite

解决方案


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

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

推荐阅读