Skip to content

Instantly share code, notes, and snippets.

@kurozumi
Last active June 1, 2016 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurozumi/f8ce6ea380881a9a8df75dbfc15eeab6 to your computer and use it in GitHub Desktop.
Save kurozumi/f8ce6ea380881a9a8df75dbfc15eeab6 to your computer and use it in GitHub Desktop.
【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