[Tutor] Getting two files to print

Andre Engels andreengels at gmail.com
Wed Jul 20 22:51:44 CEST 2005

(answer at the bottom)

On 7/18/05, Philip Carl <plc at med.unc.edu> wrote:
> I have no more hair to pull out, so I'm asking the group for help on a
> VERY simple question.  I have two very similar text files to read-one
> with the final letters in the name 10%.txt and the other 20%.txt.  I've
> written the following simple code to read these two files:
> # Program to read and print two text fiiles
> fileNameA =
> 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_10%.txt'
> #text file one
> firstFile=open (fileNameA,'r')
> inFileLeftA = 1 #more file to read
> inLineA=[0]
> while inFileLeftA:
>     inLineA = firstFile.readline()
>     if (inLineA == ''):
>         infileLeftA = 0 #if empty line end of first file
>     else:
>         print inLineA
> firstFile.close()
> fileNameB =
> 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_20%.txt'
> #text file two
> secondFile=open (fileNameB,'r')
> inFileLeftB = 1 #more file to read
> inLineB=[0]
> while inFileLeftB:
>     inLineB = secondFile.readline()
>     if (inLineB == ''):
>         infileLeftB = 0 #if empty line end of second file
>     else:
>          print inLineB
> secondFile.close()
> I realize that I probably ought to be able to code this more
> efficiently, but as a rank beginner I am less worried about efficiency
> than output.  I can't seem to get BOTH files to print  when run as
> presented, although when I split the program into two programs each file
> seems to print OK.  As written here however,  I can get the first but
> not the second textfile to print. What am I doing wrong?.

You call the variable inFileLeftA, but when you try to set it to 0,
you use the name infileLeftA instead. That's another variable, so
inFileLeftA always remains 1.

Regarding the "ought to be able to code this more efficiently": The
obvious thing to do seems to be to use a function, so you have to type
in everything once instead of twice, like this:

# start of code

def printTextFile(fn):
    # Print the contents of textfile fn
    file = open(fn,'r')
    inFileLeft = 1
    while inFileLeft:
        inLine = file.readline()
        if inLine == '':
            inFileLeft = 0
            print inLine


# end of code

There are other things that could be improved, but this is the main one by far.

Andre Engels

More information about the Tutor mailing list