Save output to file

Viewed 54

I am trying to save my output to a CSV file. I want to keep the list of floats as they are, however, my code keeps outputting them as strings. Is there any way that I can save the list as a list of floats?

This is an example of the type of data that I am trying to save to file:

x['boxes'] = [[164.5, 94.5, 174.3, 124.25], [198.45, 87.9375, 211.4, 116.8125]]
    csvData = [[x['boxes']]]
    with open('ground_truth.csv', 'a', newline='') as csvFile:
        writer = csv.writer(csvFile)
        writer.writerows(csvData)
        csvFile.close()

When I read the file I get strings

with open('ground_truth.csv', 'r') as file:
    boxes = file.read()
    print(boxes)
"[[184.4, 92.0, 15.0, 39.9375], [172.15, 89.8125, 8.0, 18.9375]]"
"[[165.5, 95.5, 10.8, 30.75], [199.45, 88.9375, 13.95, 29.875]]"
1 Answers

I have saved to csv file using pandas and able to get list of floats

Below is the code snippet you can use:

import pandas as pd

x = pd.DataFrame() # declaring x as  data frame 

x['boxes']= [[164.5, 94.5, 174.3, 124.25], [198.45, 87.9375, 211.4, 116.8125]]


x.to_csv('ground.csv')   # saving to csv file 
Related