Python – appending comma character to a row in csv file

Issue

This might be trivial, but I tried a lot and didn’t work.

I have the following piece of code:

if a == 0 and b == c-1:
    row.append(str(arrayElement[k])+"],")

The desired output at the .csv file should be similar to the following:

[1,1,2],

i.e: I want the last column in the row to contain the string 2],
however, what I am getting is this:

[1,1,"2],"

How to get the output in the format I want?

Edit: I am reading from a binary file, and the final output should be like this:

[[1,1,2],
[2,3,4],
[5,6,7]]

I succeeded writing [[,[ and ]], so the first cell in the first row contains: [[1,
the first cell in 2nd row: [2, the last cell in 2nd row 4], etc.

The full code is the following:

        k = 0
        row = []
        for M in range (X):
            for N in range(Y):
                if N != Y:
                    k = k + 1                     
                    if M == 0 and N == 0:
                        row.append("[["+str(arrayElement[k-1]))
                    elif M == 0 and N == Y -1:
                        row.append(str(arrayElement[k-1])+"],")
                    elif M == X -1 and N == Y -1:
                        row.append(str(arrayElement[k-1])+"]]")
                    elif M > 0 and N == Y -1:
                        row.append(str(arrayElement[k-1])+"],")
                    elif M > 0 and N == 0:                       
                        row.append("["+str(arrayElement[k-1]))
                    else:
                        row.append(str(arrayElement[k-1]))
            WeightsWriter.writerow(row)
            row = []

Solution

Try instead of adding the comma to the array itself, adding the comma when you add the row to the CSV file. Example:

row = [1,2,3]
csv.write(str(row)+",") # Writes [1, 2, 3], to CSV file

If you have many different rows and would like to join them with a comma you could use ",".join(rows) to join the rows with a comma. Example:

rows = []
rowa = [1,2,3]
rows.append(rowa)
rowb = [4,5,6]
rows.append(rowb)
",".join([str(_) for _ in rows]) # Outputs [1, 2, 3],[4, 5, 6]

Hope this helps!

Answered By – Alessi 42

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published