[Tutor] modify csv textfile

Sander Sweers sander.sweers at gmail.com
Sat Aug 7 12:31:44 CEST 2010


On 7 August 2010 04:35, 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
>
> #!/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.

You can test if one item in your list begins with example like:
' example125 oo3 3456'.lstrip()[:7].lower() == 'example'

lstrip() will remove any unwanted white space on the left side of the string.
slice [:7] will give you the first 7 characters from the string.
lower() will make the string lower case so your requirement for case
insensitive is met.

Then your loop would look like (untested):

for row in reader:
    if row[3].lstrip()[0:7].lower() == 'example':
         row[3] = row[3].lstrip()[:7] #we replace the fourth item.
    print row

Greets
Sander


More information about the Tutor mailing list