[英]Writing csv without csv module
Below is a line of code using the csv module but my goal is to try to implement the same code without the use of that module or pandas package while maintaining the same output. 我使用的 csv 文件是: https://drive.google.com/file/d/1PnQzoefx-IiB3D5BKVorcawoVFLIPVXQ/view?usp=sharing
以下是我目前在 Python 中的代码:
def parse_planets_file(fname) :
import csv
with open(fname) as inputfile :
reader = csv.reader(inputfile)
inputm = list(reader)
method = inputm.pop(0)
del method[0]
data = {}
for row in inputm:
if row[0] not in data:
data[row[0]] = {h:[] for h in method}
for s, a in enumerate(method):
data[row[0]][a].append(float(row[s+1]) if row[s+1] else row[s+1])
return data
fname = "exoplanets.csv"
print(parse_planets_file(fname))
另外,我的 output 包含我想跳过的 ' ' 形式的空格,我怎么会 go 呢? 谢谢!
这是解析常规格式的 CSV 的方法(如描述中链接的内容)
list_of_dicts = {}
with open('exoplanets.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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.