Put each values on next column of csv file

Hello All…i got the code below…I want to encode the result values into a csv file.

result = (" ".join(str(i) for i in list))
writer.writerow(["Values", result])

I want the result to be like this:

Col-1 Col2 Col3 Col4
Values 23 24 25

But my code result:
Col-1 Col2
Values 23 24 25

Anyone can suggest me please…thanks

import csv

field = ["Col-1", "Col2", "Col3", "Col4"]
data = [
    ["Value", 23, 24, 25],
    ["Value", 24, 25, 26],
    ["Value", 25, 26, 27],
    ["Value", 26, 27, 28],

with open("my_file.csv", "w") as f:
    writer = csv.writer(f, delimiter=";", lineterminator="\n")



you can change the delimiter to anything you want for example space " "

1 Like

I don’t really understand how you expect us to help you here… as far as I can tell, the issue is that the first line is wrong, yes? It says Col-1 Col2, but it should say Col-1 Col2 Col3 Col4?

But you didn’t show us code that has anything to do with that result. You only showed us the code to produce the Values 23 24 25 part, which seems to be working correctly.

Or did you mean, the 23 24 25 appears all in the same column when you open the file in a spreadsheet viewer, and you want it to be in separate columns instead?

That happens because " ".join(str(i) for i in list) makes a single string, and then ["Values", result] makes a list with two items - the string Values, and the joined-up string.

When you call writer.writerow with a list, there should be a separate element in the list for each cell that you want in that row. You have a list [23, 24, 25] and you want to make a list with four elements ["Values", 23, 24, 25] (note that you do not need to convert to string; the CSV writer will take care of that for you). That is simple: simply join the lists like ["Values"] + list.

As an aside, list is a poor name for that list - please use something else.

1 Like