List to csv without commas in Python

Question:

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.

Asked By: vojtam

||

Answers:

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

with open("file.csv", "w") as msg:
    msg.write(",".join(l))

For less trivial examples:

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

with open("file.csv", "w") as msg:
    msg.write(",".join([ '"'+x+'"' for x in l]))

Here you basically set every list element between quotes, to prevent from the intra field comma problem.

Answered By: Synthase

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)
    ...
Answered By: Serge Ballesta

If you want to write the entire list of strings to a single row, use csv_writer.writerow(mylist) as mentioned in the comments.

If you want to write each string to a new row, as I believe your reference to writing them in the first column implies, you’ll have to format your data as the class expects: "A row must be an iterable of strings or numbers for Writer objects". On this data that would look something like:

csv_writer.writerows((entry,) for entry in mylist)

There, I’m using a generator expression to wrap each word in a tuple, thus making it an iterable of strings. Without something like that, your strings are themselves iterables and lead to it delimiting between each character as you’ve seen.

Using csv to write a single entry per line is almost pointless, but it does have the advantage that it will escape your delimiter if it appears in the data.

To specify an encoding, the docs say:

Since open() is used to open a CSV file for reading, the file will by
default be decoded into unicode using the system default encoding (see
locale.getpreferredencoding()). To decode a file using a different
encoding, use the encoding argument of open:

import csv with open('some.csv', newline='', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

The same applies to writing in something other than the system default encoding: specify the encoding argument when
opening the output file.

Answered By: Peter DeGlopper

Try this it will work 100%

import csv
mylist = ["Hallo", "der Pixer", "Glas", "Telefon", "Der Kühlschrank brach kaputt."]
def list_na_csv(file, mylist):
    with open(file, "w") as csv_file:
        csv_writer = csv.writer(csv_file)
        csv_writer.writerow(mylist)
list_na_csv("example.csv", mylist)
Answered By: Hitesh Mishra

try split("n")
example:

counter = 0
amazing list = ["hello","hi"]
for x in titles:
        ok = amazinglist[counter].split("n")
        writer.writerow(ok)
        counter +=1
Answered By: Sara Taher
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.