首页 > 解决方案 > 如何在没有csv库python的情况下写入csv文件

问题描述

我需要在现有.csv文件上写。具体来说,我需要在文件中添加新行,但我不允许使用该csv库。有任何想法吗?

只有我被允许使用的库是:

我一直在尝试寻找答案,但我找到的只是使用csv图书馆的答案。

标签: pythoncsvappendwrite

解决方案


这是解析csv文件的方法

list_of_dicts = {}
with open('file.csv','r') as file_handle:
    file_content = file_handle.read()
for line_index, line in enumerate(file_content.split('\n')):
    if line_index==0: # header
        headers = line.split(',')
    else:
        my_data = {}
        column_entries_in_this_line = line.split(',')
        for col_index, entry in enumerate(column_entries_in_this_line):
            my_data[headers[col_index]] = entry
        list_of_dicts.append(my_data)

免责声明:您必须小心自己包含逗号、换行符或引号的值,因此这取决于您的数据的特定格式


推荐阅读