Skip to content

Instantly share code, notes, and snippets.

@kurozumi kurozumi/csv_sort_int.py

Last active Jun 1, 2016
Embed
What would you like to do?
【Python】CSVファイルの数字が正しくソートされないときの対処法
# coding: utf-8
def csv_sort(file, i=0):
import csv
with open(file, "r") as f:
reader = csv.reader(f)
# ヘッダーがあれば除外
next(reader)
# ここで数値をint型に変換してソートする
for row in sorted(reader, key=lambda x:int(x[i]) if x[i].isdigit() else x[i]):
yield row
if __name__ == "__main__":
for row in csv_sort("file.csv"):
print row
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.