Is there a simple way to match a value in a given field of a csv file using python without using a regex? I have a field in a csv file that contains text. I wish to write a python script to do stuff to all the fields that contain the text 'eagle' in a file called file.csv.
For example:
import csv
with open('file.csv', mode='r') as infile:
reader = csv.reader(infile)
for row in reader:
match = row[3]
if match == 'eagle':
DO STUFF
The above code does not work. How can I DO STUFF with all the row[3] values that match the string 'eagle'? Thanks for the help!
EDIT:开发者_如何学JAVA here are some examples lines from 'file.csv'
tree,rock,10000,eagle
plant,stone,500,owl
seed,boulder,7000,crane
fruit,pebble,60000000,hawk
I wish to match row[3] from line 1 and 4, then DO STUFF.
It works on my machine.
bash-4.1$ cat > file.csv
tree,rock,10000,eagle
plant,stone,500,owl
seed,boulder,7000,crane
fruit,pebble,60000000,hawk
bash-4.1$ python
Python 2.7 (r27:82500, Sep 16 2010, 18:03:06)
[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>>
>>> with open('file.csv', mode='r') as infile:
... reader = csv.reader(infile)
... for row in reader:
... match = row[3]
... if match == 'eagle':
... print(repr(match))
...
'eagle'
Splitting your line by ',' will works if no data contains the ',' character.
string.split(row,",")
http://docs.python.org/library/string.html
精彩评论