I have comma-delimited files like these, where the first field is sorted in increasing order:
Case 1 ( 1st file ) :
abcd,1 abcd,21 abcd,122 abce,12 abcf,13 abcf,21
Case 2 ( and another file like this ) :
abcd,1 abcd,21 abcd,122
What I want to do is convert the first file to like this :
abcd 1,21,122 abce 12 abcf 13,21
And similarly, for the second file like this :
Now, I wrote a very ugly code with a lot of if's to check whether the next line's string before the comma is same as current line's string so, if it is then do ....
It's so badly written that, I wrote it myself around 6 months back and it took me around 3-4 minutes to understand why I did what I did in this code. Well in short it's ugly, in case you would like to see, here it is ( also there's a bug currently in here and since I needed a better way than this whole code so I didn't sort it out, for the curious folks out there the bug is that it doesn't print anything for the second case mentioned above and I know why ).
def clean_file(filePath, destination): f = open(filePath, 'r') data = f.read() f.close() curr_string = current_number = next_string = next_number = "" current_numbers = "" final_payload = "" lines = data.split('\n')[:-1] for i in range(len(lines)-1): print(lines[i]) curr_line = lines[i] next_line = lines[i+1] curr_string, current_number = curr_line.split(',') next_string, next_number = next_line.split(',') if curr_string == next_string: current_numbers += current_number + "," else: current_numbers += current_number # check to avoid ',' in the end final_payload += curr_string + " " + current_numbers + "\n" current_numbers = "" print(final_payload) # For last line if curr_string != next_string: # Directly add it to the final_payload final_payload += next_line + "\n" else: # Remove the newline, add a comma and then finally add a newline final_payload = final_payload[:-1] + ","+next_number+"\n" with open(destination, 'a') as f: f.write(final_payload)
Any better solutions?