Hi all -

I need to write a code that reads in a 20 line file 4 lines at a time, and puts the five sets of 4 strings into their own individual strings. So there should be five strings containing 4 strings each.

I am very confused and havne't gotten very far in the code..

myFile = open("lab12.txt","r")
myOut = open("out.txt","w")
line1 = myFile.readline()
myString = ()




while line1 != "":
    line2 = myFile.readline()
    line3 = myFile.readline()
    line4 = myFile.readline()
    myString = (line1,line2,line3,line4)
    myOut.write(myString)
    line1 = myFile.readline()
    
myOut.close()
myFile.close()

This is not string, it is tuple. You can only write string to file.

myString = (line1,line2,line3,line4)

You can do it this way, but it would be better to use a for() loop:

ctr = 0
line1 = myFile.readline()
while line1:
    myOut.write(line1.strip("\n"))     ## 4 records without end-of-line
    ctr += 1
    if ctr > 3:                    ## 4 records written
        myOut.write("\n")
        ctr = 0

    line1 = myFile.readline()

Woooee - would that output the five strings containing 4 lines of data each? I am currently using a campus computer that doesn't have python installed..I will try it once I get home.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.