用CSV中的行n中每列的数据替换文本,运行脚本,重复

时间:2013-06-08 19:38:23

标签: python python-2.7

我有一个包含多列(固定)和N行的CSV文件。我需要将脚本中的某些文本替换为n行中每列的数据/文本,运行脚本,然后从第n + 1行重复该数据。

我所拥有的每一个想法都是非常低效的。最简单的方法是什么?

非常感谢。

皮特

1 个答案:

答案 0 :(得分:0)

标准库有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}
相关问题