[Tutor] a quick Q: how to use for loop to read a series of files with .doc end

lina lina.lastname at gmail.com
Fri Oct 7 17:22:38 CEST 2011


On Fri, Oct 7, 2011 at 11:03 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> On 07/10/11 13:21, lina wrote:
>
>     One simple explanation:  it continued on to the next file, which has
>>    neither "E" nor "B" in it.
>>
>> In this directory, I only kept one file. try.xpm
>>
>>  $ more try.xpm
>> aaEbb
>> aEEbb
>> EaEbb
>> EaEbE
>>
>> $ ls
>> counter-vertically-v2.py  try.xpm
>> counter-vertically.py   try.txt
>>
>
> That's 4 files.
> And your code will try to process all of them, including the Python
> scripts.
>


#!/usr/bin/python3

import os.path
import glob

TOKENS="BE"
LINESTOSKIP=0
INFILEEXT=".xpm"
OUTFILEEXT=".txt"


if __name__=="__main__":

    for fileName in glob.glob('*.xpm'):
        base, ext =os.path.splitext(fileName)
        text=open(fileName).readlines()
        text=text[LINESTOSKIP:]
        numcolumns=len(text[0])
        results={}
        for ch in TOKENS:
            results[ch] = [0]*numcolumns
        for line in text:
            line = line.strip()
        for col, ch in enumerate(line):
            if ch in TOKENS:
                results[ch][col]+=1
        print(results)
        summary=[]
        for a,b in zip(results['E'],results['B']):
            summary.append(a+b)
        print(summary)
        open(base+OUTFILEEXT,"w").write(str(summary))

$ more try.xpm
aaEbb
aEEbb
EaEbb
EaEbE


$ python3 counter-vertically-v4.py
{'B': [0, 0, 0, 0, 0, 0], 'E': [1, 0, 1, 0, 1, 0]}
[1, 0, 1, 0, 1, 0]


Huge unexpected problems, it's only output 1 or 0,
the summary results is not correct.



>
> I think that's a fundamental problem, you should use glob.glob() to ensure
> you only process the files you are interested in.
>
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
Best Regards,

lina
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111007/d4f686c8/attachment.html>


More information about the Tutor mailing list