[Tutor] modify csv textfile
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'
r = r.lstrip()[:len(s)]
> Input file:
> 1119|Avail|53|Potato Chips
> 1234|Avail|53|Potato Chips and salse
> 1399|Avail|53|potato chips
> 1490|Avail|64|Pretzels and mustard
> #!/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.lower()):
> row = 'Potato Chips'
> if re.match('^pretzels.*', row.lower()):
> row = 'Pretzels'
> print row
Python start numbering indexes at 0 so row 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.
More information about the Tutor