Question

I have a (python) script which iterates through objects, calculating for each object a set of values (of differing types).

For example:

+----------+---------+----------+------------------+
| 'Object' | 'width' | 'weight' | 'favorite color' |
+==========+=========+==========+==================+
| 1        | 2m      | 3kg      | blue             |
+----------+---------+----------+------------------+
| 2        | 4m      | 5kg      | blue             |
+----------+---------+----------+------------------+
| 3        | 5m      | 5kg      | green            |
+----------+---------+----------+------------------+

I want to save these values in such a way that I can sort the data by any value: i.e. reorganize the data in order of weight; get me the favorite colors of objects less than 50m wide; put in order of weight all the objects with the favorite color 'blue'...

My priority is simplicity: a method that works, yet will not take long to learn or to implement.

Was it helpful?

Solution

After investigating a few options I have settled on using csv as it is the simplest and quickest method to achieve my goal.

I can import the resultant file into an editing program (LibreOfficeCalc) specifying it contains columns separated by a comma.

import csv

thedata = [
['object', 'weight', 'width', 'favorite color'], 
[1, 5.0, 4.0001, 'blue'], 
[2, 5.4, 45.444, 'green'] 
]

myfile = 'object_values.txt'

for object_values in thedata:
    with open(myfile, 'a+') as thefile:
        wr = csv.writer(thefile)
        wr.writerow(object_values)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top