-1

I have this array of strings:

my_array = ['5.0', '6.066', '7.5', '7.83', '9.75']

and I want to write first 3 items on my csv file.

I am using this code

n=0
with open("file.csv",'w',newline="",)as e:
    while n<3:
        writer=csv.writer(e)    
        writer.writerow(my_array[n])
        n=n+1    

The output is:

5,.,0
6,.,0,6,6
7,.,5

but I don't want to separate numbers with comma for example the output must be:

5.0
6.066
7.5

What should I do?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Alireza
  • 1
  • 1
  • Try regex, in which you search for ',', and replace it with empty space ''. – Dennis Kozevnikoff Aug 16 '21 at 20:00
  • 1
    @DennisKozevnikoff or just don't write commas in the first place. – mkrieger1 Aug 16 '21 at 20:01
  • 2
    `writerow()` wants an iterable, and each element of that iterable is written as one column of the csv. Because a string is an iterable, each element (character) of that string is written to a separate column. To fix this, pass a _list_ to `writerow()` that only contains your single string – Pranav Hosangadi Aug 16 '21 at 20:04
  • 1
    Does this answer your question? [Why does csvwriter.writerow() put a comma after each character?](https://stackoverflow.com/questions/1816880/why-does-csvwriter-writerow-put-a-comma-after-each-character) – Pranav Hosangadi Aug 16 '21 at 20:07

2 Answers2

2

writerow() wants an iterable, and each element of that iterable is written as one column of the csv. Because a string is an iterable, each element (character) of that string is written to a separate column. To fix this, pass a list to writerow() that only contains your single string

You can do something like this:

import csv

my_array=['5.0', '6.066', '7.5', '7.83', '9.75']

with open('example.csv', 'w+') as f:
    writer = csv.writer(f)
    for elm in my_array[:3]:
        writer.writerow([elm])

Output of example.csv:

5.0
6.066
7.5
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
1

Apparently you don't actually want a CSV (comma separated values) file, so don't use the csv module.

Simply write each string from the list to a separate line in the file.

Some options are:

with open("file.txt", "w") as f:
    for value in my_array[:3]:
        print(value, file=f)
with open("file.txt", "w") as f:
    f.write("\n".join(my_array[:3]))
mkrieger1
  • 19,194
  • 5
  • 54
  • 65