Thomas Aurich
Thomas Aurich

Reputation: 13

Python: writing elements from a list into CSV file without brackets or quotes

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"; ...
...

Upvotes: 1

Views: 1270

Answers (2)

Eduarda Goulart
Eduarda Goulart

Reputation: 11

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")

Upvotes: 1

asthasr
asthasr

Reputation: 9407

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).

Upvotes: 0

Related Questions