3

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.

1
  • 1
    Replace "," + str(VALUE) by ", ".join(VALUE) Commented Oct 3, 2019 at 8:46

3 Answers 3

2

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

The data type of your out_string is list in your case and it is giving you list of list. To convert you can use join which will convert the datatype to str and concatenate the elements of list in your case its ",".

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

I guess it will now give you the desired output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.