Hi!

Hi!

There's three first rows that belong to the same subject. And then next three rows belong to another subject and so on, to the end of the file.

Thanks for clarifying, you're input comes in lines, and the lines are grouped in threes.

What I need to do, is put the three rows that goes together and belong to certain subject, on a one single line in the output textfile.
And that goes with the rest of the data to the end of the new file.

A few suggestions have already been posted under those general assumptions, and you should find at least one of them is practically your solution.

One thing that wasn't addressed is what happens if your file isn't an exact multiple of three lines long? What if it is 700 lines, or 802 lines? What kind of error handling/recovery do you need?

Assuming perfect input, a not too bad solution would be:

parts_so_far = []
for line in open("my-file-name-here", "rU"): # "rU" means open the file to read Universal new-lines.
    parts_so_far.append(line.rstrip())
    if len(parts_so_far) == 3:
       print "".join(parts_so_far)
       parts_so_far = []

There are lots of other ways, some better, but this should work (I tested it on some of my own local files).

If you need some text separating the lines (a space/tab/comma, whatever), you can put it in the quotes of the "".join line.

--Doug



_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to