0

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()

Edited by bigredaltoid: n/a

3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by bigredaltoid
Featured Replies
  • 1

    You can do it this way, but it would be better to use a for() loop: [code]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() [/code] Read More

0

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

myString = (line1,line2,line3,line4)
1

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()

Edited by woooee: n/a

0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.