python - 如何在没有csv库python的情况下写入csv文件
问题描述
我需要在现有.csv
文件上写。具体来说,我需要在文件中添加新行,但我不允许使用该csv
库。有任何想法吗?
只有我被允许使用的库是:
collections
dataclasses
datetime
os
random
string
sys.exit
copy
我一直在尝试寻找答案,但我找到的只是使用csv
图书馆的答案。
解决方案
这是解析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)
免责声明:您必须小心自己包含逗号、换行符或引号的值,因此这取决于您的数据的特定格式
推荐阅读
- sql - 从“LastName”按字母顺序在“Hansen”和“Peterson”之间(包括)的表中选择所有记录的 SQL 是什么?
- javascript - 如何使用 MVC asp.net 从数据库中检查由逗号分隔的模型中存在的复选框(如下面的代码所示)?
- python - 使用 dblquad 积分器发送参数的问题
- node.js - 如何在猫鼬中填充 ObjectID 的 ObjectID 数据
- sql - Elasticsearch 匹配两个字段中的任何一个
- stack - 堆栈的写时复制
- tableau-api - Tableau 中的切换选项
- wordpress - WordPress 的 PHPUnit 测试覆盖率帮助
- matlab - 你能告诉我如何解决四个未知数的四个超越方程吗?
- ios - UI 按钮上的约束问题