【问题标题】:How to write on csv file without csv library python如何在没有csv库python的情况下写入csv文件
【发布时间】:2021-10-30 02:37:30
【问题描述】:

我需要在现有的.csv 文件上写入内容。具体来说,我需要在文件中添加新行,但不允许使用 csv 库。有什么想法吗?

只有我可以使用的库是:

  • collections
  • dataclasses
  • datetime
  • os
  • random
  • string
  • sys.exit
  • copy

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

【问题讨论】:

  • 取决于您的数据有多复杂。您的数据是否包含逗号和换行符以及元素中的引号?
  • 对于简单文件,文件方法“readlines”和字符串方法“split”和“join”应该会有所帮助。

标签: python csv append write


【解决方案1】:

这是解析 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)

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

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多