[Tutor] modify csv textfile

James Mills prologic at shortcircuit.net.au
Sat Aug 7 08:40:33 CEST 2010


On Sat, Aug 7, 2010 at 12:35 PM, TGW <galaxywatcher at gmail.com> wrote:
> I have a pipe delimited text file with 5 columns which looks like this:
> 12345|some text|some more text|example125 oo3 3456|example32423
> 11223|more text|and more|example/73d 77665|example455667
> 12677|text|more|anotherexample 123|anotherexample45
>
> What I want to output is:
> 12345|some text|some more text|example|example32423
> 11223|more text|and more|example|example455667
> ...
> 12677|text|more|anotherexample 123|anotherexample45
>
> So column 4 is where the change occurs, but only if the beginning of the string in column 4  =~ /^example/i  # and it should be case insensitive

So do it :)

> #!/usr/bin/env python
> import csv
> import re
>
> filename = raw_input("Enter the filename to edit: ")
>
> reader = csv.reader(open(filename, 'rb'), delimiter='|', quoting=csv.QUOTE_NONE)
> for row in reader:
>    print row
>
> ....
> I can print the file, I just need a little help searching and replacing
the column 4 data element.

Use re.match to match the column.

Use csv.writer to write our a new csv file
based on the one you're reading, filtering
and modifying.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"


More information about the Tutor mailing list