2

I have a csv file with the following format:

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

Here, the first row represents the header, e1, e2 and e3 are my variables.

Now I want to check if there is a variable called e1.name in some text and then I want to replace it by corresponding value i.e My birthday.

Similarly if there is a variable e2.location, then it must be replaced by India. Thus I want a kind of matrix like access.

4

1 回答 1

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)

If you want a matrix form, do something like this:

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)
于 2013-04-22T06:49:21.350 回答