Skip to content
Advertisement

Concatenate text file lines with condition in python

I have a text file in this format:

JavaScript

I want to check if the image name is the same and then concatenate those lines into one line with the following format:

JavaScript

I have tried something like this but don’t know how to do the actual comparison and also don’t quite know what logic to apply since the first line_elements[0] will be taken and compared with each other line’s line_elements[0]

JavaScript

Could be something like:

JavaScript

Advertisement

Answer

Save the first field of the line in a variable. Then check if the first field of the current line is equal to the value. If it is, append to the value, otherwise write the saved line and start a new output line.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement