简体   繁体   English

无法从CSV文件中提取数据,对其进行排序,然后将该排序后的列表写入另一个CSV文件中

[英]Trouble with extracting data from a CSV file, sorting it and then writing that sorted list into another CSV file

I'm trying to read data from a CSV file, sort it in python and then write it into another CSV file. 我正在尝试从CSV文件中读取数据,以python对其进行排序,然后将其写入另一个CSV文件中。 I'm unsure of how to split the list I've sorted into the correct columns. 我不确定如何将已排序的列表拆分为正确的列。

The output file prints out the complete list and I don't know how to split the list and output it into the csv file for each column. 输出文件将打印出完整的列表,我不知道如何拆分列表并将其输出到每一列的csv文件中。

Here's a snippet of the CSV file 这是CSV文件的代码段

Jack,M,1998

Bill,F,2006

Kat,F,1999

Jess,F,2009

Alexander,M,1982

and my code to give some insight on what I'm trying to do. 以及我的代码,以便对我要执行的操作提供一些见解。

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]})

Instead of csv.DictWriter , you could use csv.writer . 可以使用csv.writer代替csv.DictWriter The loop would look like below 循环如下所示

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

Instead of sort[0] , etc.: 代替sort[0]等:

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

you meant eachline[0] , etc.: 您的意思是eachline[0]等:

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

( sort[0] , sort[1] , and sort[2] refer to three whole lines of the file, not to the three fields of one line.) sort[0]sort[1]sort[2]指的是文件的三行,而不是一行的三个字段。)

Once you've fixed that, the CSV output looks like what you want: 修复该问题后,CSV输出看起来像您想要的:

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

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

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