Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to convert list to integer and store it in csv file using python

I have some data generated in a list. I have created a csv file and it appends data in csv file.But I need to store the data as integer/string not as a list. My code is below:

VALUE = list(map(int, VALUE))
print(name, VALUE)
with open("data.csv", "a") as out_file:
        out_string =  ""
        out_string +=  "" + name
        out_string +=  "," + str(VALUE)
        out_string += "\n"
        out_file.write(out_string)

The output file is: enter image description here

I need to remove the [ and ] generated in column 2 and 17. I am not sure how to do it.

like image 939
Krupali Mistry Avatar asked Mar 27 '26 18:03

Krupali Mistry


2 Answers

You're printing an array of integers, which looks like this:

>>> x = [1,2,3]
>>> print(str(x))
[1, 2, 3]
>>>

The square brackets are Python's way to print an array. To print them as CSV lines, convert the elements to strings, and join them with a comma:

out_string +=  "," + ",".join([str(i) for i in VALUE])
like image 52
Andomar Avatar answered Mar 31 '26 05:03

Andomar


When VALUE (why uppercase, it's not a constant?) ist a list with two elements of type int and values 153 and 42, str(VALUE) will be [153,42]. When you want the output to be 153,42, you can use ','.join(VALUE) which will concatenate the elements of the list, separated by the str on which you call the join method, in this case the comma.

When writing .csv files, however, you might also want to consider using the csv module from the Python standard library.

like image 44
flaschbier Avatar answered Mar 31 '26 04:03

flaschbier