所以我只是想学习python,我正在研究一个从csv文件中获取信息的程序,然后将其输出到一个新的csv文件中。我的问题是,在输出中,数据最终是在一行而不是原来的5行。我不知道为什么,我试图在LibreOffice Calc中打开新的排序文件并且格式化已关闭,这是否与分隔符有关?感谢
import csv
import operator
name = raw_input()
myfile = name
o = open(myfile, 'rU')
mydata = csv.reader(o)
sortedlist = sorted(mydata, key=operator.itemgetter(1), reverse=True)
for row in sortedlist:
print(row[0], row[1], row[2], row[3], row[4])
o.close()
print('Enter the name for the output file')
ofile = raw_input()
with open(ofile, 'wb') as csvfile:
sortwriter = csv.writer(csvfile)
sortwriter.writerow(sortedlist)
答案 0 :(得分:0)
writerow()
一次写一行。由于您希望一次性写入所有内容,因此您需要调用其复数表兄writerows()
。
我冒昧地清理你的代码:
import csv
from operator import itemgetter
fin_name = raw_input('Enter the name for the input file')
fout_name = raw_input('Enter the name for the output file')
with open(fin_name, 'rb') as fin: # switched filemode from 'rU'. change if really needed
with open(fout_name 'wb') as fout:
reader = csv.reader(fin)
writer = csv.writer(fout)
rows = sorted(reader, key=itemgetter(1), reverse=True)
writer.writerows(rows) # changed writerow to writerows