[Baypiggies] Help with code

Drew Perttula drewp at bigasterisk.com
Sat Nov 24 02:50:25 CET 2007


Alden Meneses wrote:
> f = open('H:\xxxx\xxxx\xxxx\9-7-07')
> #File is a report that summarizes each account by account group and 
> service area then has the details for each account and Totals before the 
> next group of accounts.
> edit = ["GRP", "AREA", "CHARGES"]
> ptype = "NULL"
> area = "NULL"
> for line in f:
>     if line[:12] == 'ACCOUNT GROUP':
>         ptype = line[16:]                                   # The 
> account group starts on the 16th character of the line
>     elif line[:11] == 'SERVICE AREA':
>         area = line[11:]                                    # 
> The service area starts on the 11th character of the line
>     elif line(-1) == 'F' and line(1) != ' ':
>         edit.append(ptype,area,line[56:66])        # I wanted to append 
> the edit stack with the variables collected above.
> f.close()
> print edit

The others are correct about line[-1], but in some of these cases you 
could use string methods:

    if line.startswith('ACCOUNT GROUP'):
...
    elif line.startswith('SERVICE AREA'):
...
    elif line.endswith('F') # less important

str.startswith is easier to read and maintain, since it's got an english 
name and you don't have to count the length of your test string.



Then, edit.append takes only one argument. I'd guess you wanted to make 
a list of 3-tuples:

   edit = [("GRP", "AREA", "CHARGES")]  # len-1 list of one tuple
...
   edit.append((ptype, area, line[56:66]))  # append one item to list




Your last line is probably just for testing, but you should be aware of 
the pretty-printing library:

from pprint import pprint
...
pprint(edit)

[('GRP', 'AREA', 'CHARGES'),
  ('piggies', 'bay', '$99.99'),
  ('drew', 'bay', '$10.00')]




More information about the Baypiggies mailing list