将字符串格式化为csv

时间:2019-01-08 13:22:19

标签: python python-3.x export-to-csv

我正在尝试将python中的字典中的键和值写入csv文件。我正在获取写输出,但想对其进行格式化,以使其不包含任何“ []”或“””。尝试时:

with open(datafile, 'w', newline='', encoding='utf8') as csvfile:
    # Tab delimited to allow for special characters
    datawriter = csv.writer(csvfile, delimiter='\t')
    dic = {'2017-03-07': '36939142', '2014-02-19': '13193909'}
    for key in dic.keys():
        date = key
        order_number = dic[key]
        row = [date, order_number]
        datawriter.writerow([row])

我正在寻找csv文件中的输出。 2017-03-07,36939142.而是在输出中显示:['2017-03-07,'36939142']。

如何格式化它以获得预期的输出?

4 个答案:

答案 0 :(得分:2)

尝试datawriter.writerow(', '.join(row))作为最后一行。现在,您正在将数据作为数组写入csv文件。 ', '.join(ar)语法用括号括住数组的每个部分,并将它们之间用逗号连接起来

答案 1 :(得分:0)

尝试这样的事情:

with open(datafile, 'w', newline='', encoding='utf8') as csvfile:
    # Tab delimited to allow for special characters
    datawriter = csv.writer(csvfile, delimiter='\t')
    dic = {'2017-03-07': '36939142', '2014-02-19': '13193909'}
    for key in dic.keys():
        datawriter.writerow("%s, %s" % (key, dic[key]))

答案 2 :(得分:0)

如果您希望使用自己的解决方案,则可以将最后一行更改为

row = f"{date}, {order_number}"

答案 3 :(得分:0)

在python 3中,您可以如下实现

with open(datafile, 'w', newline='', encoding='utf8') as csvfile:
    # Tab delimited to allow for special characters
    datawriter = csv.writer(csvfile, delimiter='\t')
    dic = {'2017-03-07': '36939142', '2014-02-19': '13193909'}
    for key,value in dic.items():
        datawriter.writerow("{0}, {1}".format(key,value))