[Tutor] Reading multiple text files and writing data on one file

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Apr 13 20:30:40 EDT 2004



On Tue, 13 Apr 2004, ABDUL JABBAR SIDDIQUE wrote:

> First of all I must tell all of you that I'm new to programming. So
> please bear with me.


Hi Abdul,


Not a problem; please tell us if the explanations or answers you get are
weird.  *grin*



Let's take a look at the code:


> # Create the equivalent of: COPY MENU.TXT MENU.BAK
>
> # First open the files to read(r) and write(w)
> inp = open("S_1.OUT","r")
> outp1 = open ("O_1.csv","w")
>
> i=0
> for line in inp.readlines():
>     i=i+1
>     if i > 5 and i <= 76:
>         outp1.write((line[:12]+line[88:96])+"\n")
>
> print "1 file copied..."
>
> # Now close the files
> inp.close()
> outp1.close()


It's possible to 'for loop' across a file without having to read all of
its lines at once.  You may want to rewrite the loop from:

###
for line in inp.readlines():
    ...
###


to:


###
for line in inp:
    ...
###


This becomes more important when the files get much larger.





> I dont know how to further read selected data from say "S_2.OUT, S_3.OUT
> etc" and write it to the same file i.e. "outp1.csv.


Just to verify: for each of the other files, do you also want to restrict
the captured lines from the 5th through to the 76th's lines?


It sounds like you want to repeat the process of:

###
i=0
for line in inp:
    i=i+1
    if i > 5 and i <= 76:
        outp1.write((line[:12]+line[88:96])+"\n")
###

over and over, for S_2.OUT, S_3.OUT, etc.  Let's first give a name to this
process:

###
def process(inp, outp):
    i=0
    for line in inp:
        i=i+1
        if i > 5 and i <= 76:
            outp.write((line[:12]+line[88:96])+"\n")
###





If we have this function, then the program can look like this:

###
def process(inp, outp):
    i=0
    for line in inp:
        i=i+1
        if i > 5 and i <= 76:
            outp.write((line[:12]+line[88:96])+"\n")


inp = open("S_1.OUT","r")
outp1 = open ("O_1.csv","w")
process(inp, outp1)
print "1 file copied..."

# Now close the files
inp.close()
outp1.close()
###

Does this make sense so far?




Hope this helpS!




More information about the Tutor mailing list