[Tutor] converting xls to csv

Kent Johnson kent37 at tds.net
Sun Jun 7 06:11:44 CEST 2009


On Sat, Jun 6, 2009 at 5:37 PM, Nick Burgess<burgess.nick at gmail.com> wrote:
> Thanks everyone, the following code works great.  It returns the name
> of the file and the row that matched the reqex.  Is it posible to take
> the regex compile from user input?  To make it take an argument,  like
>
>> csvSearch.py 10.192.55
>
> af = re.compile(sys.argv[1])
> pattern = re.compile(af)          ....?

You only have to compile it once, but you should escape it so .
becomes \. like this:
pattern = re.compile(re.escape(sys.argv[1])

> pattern = re.compile(r'10\.191\.2')
> files = glob.glob("*.csv")
>
> for f in files:
>    ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|')
>    for row in f:

You don't need the above, it is iterating over the characters of the file name.

>        for row in ff:
>            for cell in row:
>                if pattern.search(cell):

The above two lines can be written as
  if any(pattern.search(cell) for cell in row):

Kent


More information about the Tutor mailing list