[Tutor] modify csv textfile

Sander Sweers sander.sweers at gmail.com
Sat Aug 7 16:19:05 CEST 2010


On 7 August 2010 13:45, TGW <galaxywatcher at gmail.com> wrote:
>> You can test if one item in your list begins with example like:
>> ' example125 oo3 3456'.lstrip()[:7].lower() == 'example'
>
> I think I need to use regex here. Perhaps you will agree.

You could but you don't have to, consider this.

r = '1234|Avail|53|Potato Chips and salse'.split('|')
s = 'potato chips'

if r[3].lstrip().lower().startswith(s):
    r[3] = r[3].lstrip()[:len(s)]
    print r

> Input file:
> 1119|Avail|53|Potato Chips
> 1234|Avail|53|Potato Chips and salse
> 1399|Avail|53|potato chips
> 1445|Avail|64|Pretzels
> 1490|Avail|64|Pretzels and mustard
> etc...
>
> #!/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:
>    if re.match('potato chips.*', row[4].lower()):
>        row[4] = 'Potato Chips'
>
>    if re.match('^pretzels.*', row[4].lower()):
>        row[4] = 'Pretzels'
>
>    print row

Python start numbering indexes at 0 so row[4] is the *5th* item item
in your list.

> Row will be variable length, so strip() will not work for me.

I did not use strip() but lstrip() and only to remove leading
whitespace..? However strip only removes the _leading and trailing_
whitespace or character(s) you pass it.

> But neither does my latest attempt ^^

With the info and example data provided this would surely have given
an IndexError. So if you run into an exception you need to provide
them as they will be giving clues where it is going wrong.

Greets
Sander


More information about the Tutor mailing list