newbie write to file question

Scott David Daniels scott.daniels at acm.org
Sun Dec 4 11:57:00 EST 2005


ProvoWallis wrote:
...
> for root, dirs, files in os.walk(setpath):
>      fname = files
>      for fname in files:
>           inputFile = file(os.path.join(root,fname), 'r')
>           while 1:
>                lines = inputFile.readlines(10000)
>                if not lines:
>                     break
>                for line in lines:
>                     ...
Is pretty verbose.  Also, open is meant to be the function to use.
Try:
     for root, dirs, files in os.walk(setpath):
        for fname in files:
            inputFile = open(os.path.join(root,fname), 'r')
            for line in inputFile:
                ...
            inputFile.close()


There is no point to lines like:
 >                     if main is None:
 >                          pass
Just drop it.

Perhaps what you meant was:
                       if main is None:
                            continue
If so, change:
>                     if main is not None:
>                          table[main.group(1)] = main.group(2)
>                          m = main.group(1)
 >                     if main is None:
 >                          pass
To:
                       if main is None:
                           continue
                       table[main.group(1)] = main.group(2)
                       m = main.group(1)

As Rob E pointed out, your postlude has the wrong indentation.
You may want:
     for root, dirs, files in os.walk(setpath):
        for fname in files:
            inputFile = open(os.path.join(root, fname), 'r')
            for line in inputFile:
                ...
            inputFile.close()
            if table:
                name, ext = os.path.splitext(fname)
                output_name = name + '.log'
                outputFile = open(os.path.join(root, name + '.log'), 'w')
                outputFile.write(str(table))
                outputFile.close()
                table = {}
So that you only write logs if something was found.


-- 
-Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list