Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write float list to csv file

Tags:

python

csv

I have a list of float numbers, its format is:

float_list = [1.13, 0.25, 3.28, ....]

I used following code to write it to a .csv file:

float_str = ""

for result in result_list:
    float_str = float_str + str(result.get_value()) + ","

with open(output_path, "wb") as file:
    writer = csv.writer(file)
    writer.writerow(float_str)

file.close()

where result.get_value() is:

def get_value():
    return float(value)

I expect to see that in each cell, there is a value. However, what I've got looks like:

1   .   1   3   ,    0   .   2    5   ,  3   .   2   8   ,

It seems that each of the digits occupies a cell.

So, may I know how can I solve this issue and get what I expected?

like image 654
ChangeMyName Avatar asked Jan 29 '14 14:01

ChangeMyName


People also ask

How do I make a list into a csv file?

The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating a CSV file and writing data row-wise into it using writer class.

How do I write a list of elements in a csv file in Python?

The student. csv is the name of the file, the “w” mode is used to write the file, to write the list to the CSV file write = csv. writer(f), to write each row of the list to csv file writer. writerow() is used.

Can you write directly to a csv file in Python?

To write to a CSV file in Python, we can use the csv. writer() function. The csv. writer() function returns a writer object that converts the user's data into a delimited string.


1 Answers

The writer.writerow() takes a sequence (a list or tuple), but you are passing in a string instead. By passing in a string, writer.writerow() still treats it as as sequence, and each individual character becomes a column value:

1,.,1,3,,,0,.,2,5,,,3,.,2,8

Moreover, the method converts column to strings for you, don't do this yourself.

Instead build a list of your float values and pass that in:

row = []
for result in result_list:
    row.append(result.get_value())

with open(output_path, "wb") as file:
    writer = csv.writer(file)
    writer.writerow(row)

or even:

with open(output_path, "wb") as file:
    writer = csv.writer(file)
    writer.writerow([r.get_value() for r in result_list])

The delimiter defaults to ,.

like image 146
Martijn Pieters Avatar answered Sep 23 '22 12:09

Martijn Pieters