【问题标题】:Trouble with extracting data from a CSV file, sorting it and then writing that sorted list into another CSV file从 CSV 文件中提取数据、对其进行排序然后将该排序列表写入另一个 CSV 文件时遇到问题
【发布时间】:2016-10-20 00:45:38
【问题描述】:

我正在尝试从 CSV 文件中读取数据,在 python 中对其进行排序,然后将其写入另一个 CSV 文件。我不确定如何将已排序的列表拆分为正确的列。

输出文件打印出完整的列表,我不知道如何拆分列表并将其输出到每个列的csv文件中。

这是 CSV 文件的 sn-p

Jack,M,1998

Bill,F,2006

Kat,F,1999

Jess,F,2009

Alexander,M,1982

和我的代码,让我对我正在尝试做的事情有所了解。

import csv
import operator

   US = open('Test.csv', 'r')#Unsorted
   S = open('TestSorted.csv', 'w')#Sorted

def sortinput():
            option = input('Sort by name, gender or year?: ')
            if option == "name":
                choice = 0
            elif option == "gender":
                choice = 1
            elif option == "year":
                choice = 2
            else:
                print('Invalid Input')

            csv1 = csv.reader(US, delimiter=',')
            sort = sorted(csv1, key=operator.itemgetter(choice))

            for eachline in sort:
                    print (eachline)

            with S as csvfile:
                    fieldnames = ['Name', 'Gender', 'Year']
                    csv2 = csv.DictWriter(csvfile, fieldnames=fieldnames)
                    csv2.writeheader()
                    for eachline in sort:
                            csv2.writerow({'Name': sort[0] ,'Gender': sort[1],'Year':sort[2][enter image description here][1]})

【问题讨论】:

  • "Trouble with" 究竟是什么意思?给minimal reproducible example
  • 第 1 步:您要解决什么问题?
  • 哦,对了,对不起。输出文件打印出完整的列表,我不知道如何拆分列表并输出到每列的csv文件中。

标签: python sorting csv


【解决方案1】:

代替sort[0]等:

    for eachline in sort:
        csv2.writerow({'Name': sort[0], 'Gender': sort[1], 'Year': sort[2]}) 

你的意思是eachline[0]等:

    for eachline in sort:
        csv2.writerow({'Name': eachline[0], 'Gender': eachline[1], 'Year': eachline[2]})

sort[0]sort[1]sort[2] 指的是文件的整整三行,而不是一行的三个字段。)

修复该问题后,CSV 输出看起来就像您想要的那样:

Name,Gender,Year
Alexander,M,1982
Bill,F,2006
Jack,M,1998
Jess,F,2009
Kat,F,1999

【讨论】:

  • 谢谢!我知道它很接近,但我无法弄清楚发生了什么。欣赏它:)
【解决方案2】:

您可以使用csv.writer,而不是csv.DictWriter。循环如下所示

  with S as csvfile:
      fieldnames = ['Name', 'Gender', 'Year']
      csv2 = csv.writer(csvfile,quoting=csv.QUOTE_ALL)
      csv2.writerow(fieldnames)
      csv2.writerow(sort)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 2021-10-16
    • 2014-12-02
    • 2013-07-20
    • 2015-12-24
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多