简体   繁体   English

Python:将列表中的元素写入 CSV 文件,不带括号或引号

[英]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.我正在努力处理写入 CSV 文件的列表元素。

I wrote a Python script selecting some 25 human languages from a CSV file and put them into a list.我编写了一个 Python 脚本,从 CSV 文件中选择了大约 25 种人类语言并将它们放入列表中。 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:之后,我创建一个新的空列表并用 0 到 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:当我打印lang_skills时,它看起来像这样:

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

In the last step, I want to write the lang_skills into a new CVS file.在最后一步中,我想将lang_skills写入一个新的 CVS 文件。

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:然而,CSV 看起来像这样:

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

How can write the output like this:怎么可以这样写output:

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

You can convert your list into a pandas dataframe, to create a CSV you need the columns name and your list of value:您可以将列表转换为 pandas dataframe,以创建 CSV 您需要列名称和值列表:

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

You are trying to write a string to the CSV, not a list;您正在尝试将字符串写入 CSV,而不是列表; you want to write the string "Urdu, Ukrainian, Swedish" to the file, so you need to produce that string beforehand.您想将字符串"Urdu, Ukrainian, Swedish"写入文件,因此您需要事先生成该字符串。 Try joining the languages with ", ".join(lang_skills) .尝试使用", ".join(lang_skills)加入语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM