用python中的CSV文件替换变量值

时间:2013-04-22 06:31:45

标签: python variables csv header

我有一个csv文件,格式如下:

variable,     name,   date,       location, youtube, 
 e1,      My birthday, 21st april, USA,    www.xyz.com
 e2,      your b'day,  1st May,   India,   www.abc.com
 e3,      christmas ,  25th Dec,  UK,      www.christmas.com

此处,第一行代表标题,e1e2e3是我的变量。

现在我想检查一些文本中是否有一个名为e1.name的变量,然后我想用相应的值替换它,即My birthday

同样,如果存在变量e2.location,则必须将其替换为India。因此,我想要一种像访问这样的矩阵。

1 个答案:

答案 0 :(得分:2)

import csv
with open('test.csv') as f:
    fieldnames = ('variable', 'name', 'date', 'location', 'youtube')
    r = csv.DictReader(f, fieldnames)
    next(f, None) # skip header
    rows = []
    for row in r:
        if row['variable'] == 'e1':
            row['name'] = 'My birthday'
        if row['variable'] == 'e2':
            row['location'] = 'India'
        rows.append(row)
    w = csv.DictWriter(a_file, fieldnames)
    w.writerows(rows)

如果您需要矩阵形式,请执行以下操作:

import csv
with open('test.csv') as f:
    next(f, None) # skip header
    rows = list(csv.reader(f))
    rows[0][1] = 'My birthday'
    rows[1][3] = 'India'
    w = csv.writer(a_file)
    w.writerows(rows)