[英]replacing text with data from each column in row n in CSV, running script, repeating
我有一个包含多列(固定)和N行的CSV文件。 我需要用n行中每列的数据/文本替换脚本中的某些文本,运行脚本,然后对n + 1行中的数据进行重复。
我曾经有过的每一个想法都效率很低。 最简单的方法是什么?
非常感谢。
皮特
标准库具有用于处理逗号分隔文件的csv
。 但是,如果需要unicode支持,则需要找到第三方替代品。 通常,您要描述的任务可以按以下步骤完成:
import csv
data_structure = {'id1': 123, 'id2': 456} # identifiers and values
fsock = open(file_path, 'rU')
# rdr = csv.reader(fsock) # this will read the CSV data, producing lists
dict_rdr = csv.DictReader(fsock) # read data as dictionary, using first row as keys
# if you want to read all the rows...
for entry in dict_rdr:
# update the data structure with data from the file
data_structure[entry['id_column']] = entry['value_column']
fsock.close()
该文件将如下所示:
id_column,value_column
id1,789
id2,666
脚本运行后,数据结构将为:
data_structure = {'id1': 789, 'id2': 666}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.