0

複数の列 (固定) と N 行の CSV ファイルがあります。スクリプト内の特定のテキストを n 行のすべての列のデータ/テキストに置き換え、スクリプトを実行し、n+1 行のデータで繰り返す必要があります。

私が持っていたすべてのアイデアは、本当に非効率的です。これを行う最も簡単な方法は何ですか?

どうもありがとう。

ピート

4

1 に答える 1

0

標準ライブラリにはcsv、カンマ区切りファイルを処理するためのライブラリがあります。ただし、ユニコードのサポートが必要な場合は、サードパーティの代替品を見つける必要があります. 一般に、説明しているタスクは次のように実行できます。

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}
于 2013-06-08T19:50:54.213 に答える