我想创建一个函数re_order,该函数在运行时读取一个csv文件并写出翻转到第二个文件上的前两列。定界符是一个逗号,并且假定总会有2个逗号。以下是测试文件:
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
关于如何执行此操作的任何想法?
答案 0 :(得分:0)
以下函数重新排序将文件路径作为参数,并创建一个仅翻转了前两列的新文件(在您的情况下,标题和作者列被翻转)。您的问题太含糊,我可能误解了这个问题。让我知道是否需要不同的输出。
def reorder(in_file='books.csv', out_file='books_author.csv'):
with open(in_file, "r") as f:
data = f.readlines()
fh = open(out_file, "w")
for line in data:
line = line.split(",")
fh.write(line[1] + ' ' + line[0] +'\n')
fh.close()