Reputation: 33
I have a csv with rows of data I need to parse through. I am checking for equality across different lines and sending lines that are the same into their own files. For instance:
ABC
ABC
ABC
ACB
ACB
ACB
BCA
BCA
BCA
All instances of ABC, ACB, and BCA need to be separated into their own files. That part is easy enough but each row will have a unique file name at the end of it. How can I check each row without the last element of the row?
I'm expecting some way of using len(row)-1
but not sure where that will fit into the wider syntax.
Edit:
Editing to say you all have been super helpful! row[:-1] was exactly what I needed.
Also I'm new to posting here so if there was a way to set an answer as having solved my issue I've missed it. But thanks to all of you!
Upvotes: 1
Views: 95
Reputation: 20808
As suggested in the comments, open the file, read the lines as an array, pop the last line, and write the file back somewhere else.
with open(filename, 'r') as f:
rows = f.readlines()
rows = rows[:-1]
with open(output_file, 'w') as f2:
f2.writelines(rows)
Upvotes: 0