Home > Net >  How can you loop through lines of text and join if the lines are shorter than 50 characters?
How can you loop through lines of text and join if the lines are shorter than 50 characters?

Time:11-18

I am trying to loop through each line of text in a document and if the line is shorter than 50 characters, then join them together.

What I am having trouble figuring out is the hierarchy of the loop. What I have right now is:

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        for index, line in enumerate(lines):
            if len(line) > 50:
                f2.write(line)
            else:
                # Something that would take the next line and join to the current index
                line1 = line

I need to keep the current line and then loop again for the next line to join. Could I use a while loop and add the line from the next index?

CodePudding user response:

This would concatenate lines until it sees a line with more than 50 characters.

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        prev_line = ""
        for index, line in enumerate(lines):
            if len(line) > 50:
                f2.write(prev_line   line)
                prev_line = ""
            else:
                prev_line  = line

If you need to write once the concatenated line reaches 50 characters:

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        prev_line = ""
        for index, line in enumerate(lines):
            line  = prev_line
            if len(line) > 50:
                f2.write(line)
                prev_line = ""
            else:
                prev_line  = line
  • Related