I was looking and reading previous questions and answers similar to mine, but didn't find a good solution to my case.
I have a csv file with 2 columns. One is numerical values (100, 40, 350 etc.), and the other is a list of pictures tag name (i.e. computer.jpg).
What I am trying to do is to sort the file by the first column (i.e. the values) in ascending manner. That also means that I want the pair of the value (the image name) to move accordingly with it.
This is what I have so far:
import csv
import operator
sample=open('random.csv', "r")
csv1=csv.reader(sample, delimiter='.')
header=next(csv1, None)
sort= sorted(csv1, key=operator.itemgetter(0))
with open('randomized.csv', "wb") as f:
csv_writer=csv.writer(f, delimiter='.')
if header:
csv_writer.writerow(header)
csv_writer.writerows(sort)
The resulted sorted list, however, is like this: 100, 175, 20, 250, 3.
I tried some other codes, like this:
sort=csv1.sort(key=lambda row: row[0], reverse=True)
But I receive an error back: AttributeError: '_csv.reader' object has no attribute 'sort'
I read about one option which is to convert the numbers to strings before sorting, and then converting them back to numbers before writing the file, but don't really have the tools to do it.
Anyone has a clue how to get this one down?