1 回答
TA贡献1866条经验 获得超5个赞
有很多方法可以做到这一点,但从csv 库文档中的一些示例开始,这些示例展示了如何读取csv文件和写入新csv文件。
import csv
header = []
rows = []
sortedrows = []
with open('data.csv', 'r') as f:
reader = csv.reader(f)
# grab only the first row as the header/column labels
header = next(reader, None)
# read the csv data into list `rows`
rows = list(reader)
for row in rows:
# convert all values to float for easy comparison
nums = map(float, row)
# sort values in descending order
sortedrows.append(sorted(nums, reverse=True))
# write sorted data to a new csv file
with open('sorted.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(sortedrows)
sorted.csv 应包含所需的结果:
NumberA,NumberB
22.0,10.0
44.0,33.0
779.7,776.4
78.0,77.0
在 Excel 中查看:
添加回答
举报