我编写了以下代码:
import sys, csv, operator
data = csv.reader(open('books.csv'),delimiter=',')
header = next(data)
print (header)
sortedlist = sorted(data, key=operator.itemgetter(1))
with open("books_sort.csv", "wb") as f:
# fileWriter = csv.writer(f, delimiter=',')
fileWriter = csv.writer(f)
# fileWriter.writerows(header)
# fileWriter.writerows(sortedlist)
for row in sortedlist:
print (row)
# f.writerows(row)
此代码的目的是获取一个内容在各列中的文件,并仅根据第二列将其按字母顺序排列。然后,它将所需的结果输出到新文件中。我上面的代码可以打印所需的结果,但是当我尝试使其输出包含该结果的新文件时,它将无法正常工作。您可以在上面的注释中看到我尝试编写新文件的部分。伙计们对此有什么想法吗?在你们中的任何人说使用熊猫是更简单的方法之前,我明确不允许这样做。以下是我文件的内容:
Title, Author, Publisher, Year, ISBN-10, ISBN-13
Automate the..., Al Sweigart, No Sta..., 2015, 15932..., 978-15932...
Dive into Py..., Mark Pilgr..., Apress, 2009, 14302..., 978-14302...
"Python Cook..., "David Bea..., O'Reil..., 2013, 14493..., 978-14493...
Think Python..., Allen B. D..., O'Reil..., 2015, 14919..., 978-14919...
"Fluent Pyth..., Luciano Ra..., O'Reil..., 2015, 14919..., 978-14919...
答案 0 :(得分:0)
看来您正在使这项工作变得不必要。首先,让我们清理示例数据,因为不匹配的双引号会使cvs.reader
混乱:
Title,Author,Publisher,Year,ISBN-10,ISBN-13
Automate the...,Al Sweigart,No Sta...,2015,15932...,978-15932...
Dive into Py...,Mark Pilgr...,Apress,2009,14302...,978-14302...
"Python Coo...",David Beaz...,O'Reil...,2013,14493...,978-14493...
Think Python...,Allen B. D...,O'Reil...,2015,14919..., 978-14919...
"Fluent Pyt...",Luciano Ra...,O'Reil...,2015,14919...,978-14919...
接下来,让我们根据cvs模块文档构建一个程序:
import csv
import operator
data = csv.reader(open('books.csv', newline=''), delimiter=',')
header = next(data)
sortedlist = sorted(data, key=operator.itemgetter(1))
with open("books_sorted.csv", "w", newline='') as csvfile:
cvsWriter = csv.writer(csvfile, delimiter=',')
cvsWriter.writerow(header)
cvsWriter.writerows(sortedlist)
哪个会生成包含以下内容的输出文件:
Title,Author,Publisher,Year,ISBN-10,ISBN-13
Automate the...,Al Sweigart,No Sta...,2015,15932...,978-15932...
Think Python...,Allen B. D...,O'Reil...,2015,14919..., 978-14919...
Python Coo...,David Beaz...,O'Reil...,2013,14493...,978-14493...
Fluent Pyt...,Luciano Ra...,O'Reil...,2015,14919...,978-14919...
Dive into Py...,Mark Pilgr...,Apress,2009,14302...,978-14302...
缺少双引号,但希望正确。在注释掉的代码中,您在单行中调用了writerows()
#fileWriter.writerows(header)
for row in sortedlist:
print (row)
# f.writerows(row)
我们不应该期望它起作用。在这里,您将改用writerow()
。