0

I am struggeling with the elements of a list written to CSV file.

I wrote a Python script selecting some 25 human languages from a CSV file and put them into a list. The idea is to randomly create content that can result into a fake CV for machine learning:

# languages
all_langs = []
    
#populate languges from a central language csv
with open('sprachen.csv', newline='', encoding="utf-8") as csvfile:
    file_reader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in file_reader:
        if row[0] == "Sprache":
            continue
        else:
            all_langs.append(format(row[0]))

After that, I create a new empty list and fill it with the initial languages in a range from 0 to 3:

lang_skills = []
ran_number = random.randint(1,3)
for i in range(0,ran_number):
    lang_skills.append(str(all_langs[random.randint(0,len(all_langs)-1)]))

When I print the lang_skills it looks like this:

['Urdu', 'Ukrainian', 'Swedish']

In the last step, I want to write the lang_skills into a new CVS file.

with open('liste.csv', 'a+', newline='', encoding="utf-8") as csvfile:
    writer = csv.writer(csvfile, delimiter=';',quotechar='"', quoting=csv.QUOTE_ALL)
    writer.writerow(lang_skills)

However, the CSV looks like this:

Language
"Urdu";"Ukrainian";"Swedish"
...

How can write the output like this:

Language
"Urdu, Ukrainian, Swedish"; ...
...
Burhan Ali
  • 2,258
  • 1
  • 28
  • 38
  • Does this answer your question? [Dump a NumPy array into a csv file](https://stackoverflow.com/questions/6081008/dump-a-numpy-array-into-a-csv-file) – dǝɥɔS ʇoıןןƎ Jun 25 '20 at 11:49

2 Answers2

1

You can convert your list into a pandas dataframe, to create a CSV you need the columns name and your list of value:

import pandas as pd
my_list = ['a', 'b', 'c']
df = pd.DataFrame({'col': my_list})
df.to_csv("path/csv_name.csv")
0

You are trying to write a string to the CSV, not a list; you want to write the string "Urdu, Ukrainian, Swedish" to the file, so you need to produce that string beforehand. Try joining the languages with ", ".join(lang_skills).

asthasr
  • 9,125
  • 1
  • 29
  • 43
  • Good approach. I added: `lang_skills = " ".join(lang_skills)` Now the result looks like this: `T;ü;r;k;i;s;c;h; ;F;r;a;n;z;ö;s;i;s;c;h; ;H;i;n;d;i` – Thomas Aurich Jul 01 '20 at 13:30
  • Looks like you need to wrap the result in an iterable, e.g. `lang_skills = [" ".join(lang_skills)]`. It's treating each character as its own "cell." – asthasr Jul 01 '20 at 19:44