我有一个包含以下内容的文件:
减少可读性:
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...
全文:
Title,Author,Publisher,Year,ISBN-10,ISBN-13
Automate the Boring Stuff with Python,Al Sweigart,No Starch Press,2015,1593275994,978-1593275990
Dive into Python 3,Mark Pilgrim,Apress,2009,1430224150,978-1430224150
"Python Cookbook, Third edition","David Beazley, Brian K Jones",O'Reilly Media,2013,1449340377,978-1449340377
Think Python: How to Think Like a Computer Scientist,Allen B. Downey,O'Reilly Media,2015,1491939362,978-1491939369
"Fluent Python: Clear, Concise, and Effective Programming",Luciano Ramalho,O'Reilly Media,2015,1491946008,978-1491946008
我想读文件,写一个新的文件,包含这些相同的内容,除了第二列(作者)按字母顺序排列。标题(第一行)不应更改。有什么办法吗?作者顺序如下:
Al
Allen
David
Luciano
Mark
编辑:很抱歉没有提到这一点,但我不能使用熊猫。此外,必须根据第二列一起调整所有列。我不能向你们解释这些信息。你知道吗
编辑:我编写了以下函数,用于打印所需的排序结果,但在需要将数据写入新文件时不起作用:
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)
熊猫很适合这样做:
文档用于read_csv,sort_values,to_csv
使用pandas:
非
pandas
解决方案涉及按第二列读取文本排序:输出:
相关问题 更多 >
编程相关推荐