File Management

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Oct 15 15:51:14 EDT 2008


erict1689 a écrit :
> I am writing this program in which I open up a file and update that
> information but to a new file.  I already have a global variable for
> it 

A global variable ??? WHY ???

> but how do I go about creating an openable file in the source code?

It's in the FineManual(tm)

>  If it helps here is what I have:
> 
> def startUp():
>     # Purpose: opens files and print report headings
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>     payFile=open("payroll.txt", "r")
>     payFile.readline()
>     
> 
> def readRecord():
>     # Purpose: reads a record
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
> 
>     employeeRec = payFile.readline()
>     if employeeRec == "":
>         eof = True
>     else:
>         # parse file line for record fields and format/convert for
> final output
>         empName = employeeRec[0:25].strip()
>         previousYTD = float(employeeRec[25:40])
>         payRate = float(employeeRec[40:55])
>         hoursWorked = float(employeeRec[55:70])
>         recordCount += 1
>         eof = False
> 
> def writeRecord():
>     # Purpose: writes the updated record to the output file
>     #Parameter
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>    
> def processRecords():
>     # Purpose: loops through input file and processes each record
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>     
>     while not eof:
>         calculatePay()
>         printReportLine()
>         writeRecord()
>         readRecord()
> 
> def calculatePay():
>     # Purpose: calculates pay and updated YTD
>     # Return values: float - calculated pay, float - updated YTD amount 
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>     
> def printReportLine():
>     # Purpose: prints employee pay information
>     # Parameters passed: float - calculated pay, float - updated YTD
> amount
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
> 
> def closeUp():
>     # Purpose: end of program housekeeping
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>    
>     payFile.close()
>     payFileUpdated.close()
>     print "\nNumber of records in the file was",recordCount


OMG ! Good Ole Almighty Procedural Programming (With Lots Of Useless 
Gobals(tm)) is back ! Where have you been these 20 last years ???

> Any and all help is appreciated.

Err... Python is not BASIC ?-)

Not tested, but you may be interested in another approach (which *also* 
contains the answer to your question)...


import sys

def parse_field(slice, transform, line):
     return transform(line[slice].strip())

# key => processing function mapping
INFIELDS = dict(
     emp_name=partial(parse_field, slice(0,25), lambda x : x),
     previous_ytd=partial(parse_field, slice(25,40), float),
     payrate=partial(parse_field, slice(40,55), float),
     hoursworked=partial(parse_field, slice(55,70), float)
     )

def parse_line(line):
     """
     parse a line and return a record (key=>value mapping) from it
     """
     return dict(
         (fname, parse(line))
         for fname, parse in INFIELDS.items()
         )

def calculate_pay(record):
     """
     calculate pay etc and returns updated record with additional fields
     """
     # dummy code
     record['yadda'] = "yadda"
     return record

def format_record(record):
     """
     returns a formatted string for output
     """
     # dummy code, assuming output is csv like format
     return "%(emp_name)s;%(payrate)s;%(yadda)s" % record

def print_report_line(record):
     """ print tracing / debugging info on stderr """
     print >> sys.stderr, record

def process_line(lineno, line):
     """
     parse a line, compute pay, and return a nicely formatted output
     """
     source = parse_line(line)
     source['num_record'] = lineno
     dest = calculate_pay(source)
     print_report_line(dest)
     return format_record(dest)

def main(infile, outfile):
     """
     process lines from infile and write the result to outfile
     """
     for lineno, line in enumerate(infile):
         line = line.strip()
         if line:
             print >> outfile, process_line(lineno, line)

if __name__ == '__main__':
     #
     # the boring part...  would better be done using optparse...
     #
     # we expect two optional params:
     # 1/ the path to an input file - default to stdin
     # 2/ the path to an output file - default to stdout
     #
     try:
         infile = open(args[0])
     except IndexError:
         infile = sys.stdin
     except IOError, e:
         sys.exit(
             "could not open file %s for reading : %s" \
              % (args[0], e)
             )
     try:
         outfile = open(args[1], 'w')
     except IndexError:
         outfile = sys.stdout
     except IOError, e:
         if infile is not sys.stdin:
             infile.close()
         sys.exit(
             "could not open file %s for writing : %s" \
              % (args[1], e)
             )
     try:
         # processing
         main(infile, outfile)
     finally:
         # housekeeping...
         if infile is not sys.stdin:
             infile.close()
         if outfile is not sys.stdout:
             outfile.close()


HTH



More information about the Python-list mailing list