Skip to content
Advertisement

List to csv without commas in Python

I have a following problem. I would like to save a list into a csv (in the first column). See example here:

import csv

mylist = ["Hallo", "der Pixer", "Glas", "Telefon", "Der Kühlschrank brach kaputt."]


def list_na_csv(file, mylist):

    with open(file, "w", newline="") as csv_file:
        csv_writer = csv.writer(csv_file)

        csv_writer.writerows(mylist)


list_na_csv("example.csv", mylist)

My output in excel looks like this: enter image description here

Desired output is: enter image description here

You can see that I have two issues: Firstly, each character is followed by comma. Secondly, I don`t know how to use some encoding, for example UTF-8 or cp1250. How can I fix it please?

I tried to search similar question, but nothing worked for me. Thank you.

Advertisement

Answer

You have two problems here.

  1. writerows expects a list of rows, said differently a list of iterables. As a string is iterable, you write each word in a different row, one character per field. If you want one row with one word per field, you should use writerow

     csv_writer.writerow(mylist)
    
  2. by default, the csv module uses the comma as the delimiter (this is the most common one). But Excel is a pain in the ass with it: it expects the delimiter to be the one of the locale, which is the semicolon (;) in many West European countries, including Germany. If you want to use easily your file with your Excel you should change the delimiter:

     csv_writer = csv.writer(csv_file, delimiter=';')
    

After your edit, you want all the data in the first column, one element per row. This is kind of a decayed csv file, because it only has one value per record and no separator. If the fields can never contain a semicolon nor a new line, you could just write a plain text file:

...
with open(file, "w", newline="") as csv_file:
    for row in mylist:
        print(row, file=file)
...

If you want to be safe and prevent future problems if you later want to process more corner cases values, you could still use the csv module and write one element per row by including it in another iterable:

...
with open(file, "w", newline="") as csv_file:
    csv_writer = csv.writer(csv_file, delimiter=';')
    csv_writer.writerows([elt] for elt in mylist)
    ...
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement