python - 无法在 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
非常感谢
解决方案
上下文管理器存在缩进问题。尝试这个:
def append_list(file_name, list_of_elem):
with open(file_name, 'a+', newline='') as write_obj:
write_obj.writestr(list_of_elem)
推荐阅读
- node.js - 在 node.js 应用程序上保持打开数据库连接是一种好习惯吗?
- assembly - 尝试打印号码时出错
- reactjs - formik表单验证不起作用reactjs
- c++ - PolyHook x64Detour 未连接到 Direct3DCreate9
- git - 使用 Nix 的 Git 时权限被拒绝(公钥)
- angular - Angular v6 - 延迟加载的路由未加载
- javascript - 当我上床睡觉时,React Modal 正在工作
- javascript - 如何在本地应用程序目录中安装 nodejs 模块?
- scrape - 从抓取的表中删除 '\n'
- python - 从文件中读取和修改行