Last active
June 1, 2016 10:29
-
-
Save kurozumi/f8ce6ea380881a9a8df75dbfc15eeab6 to your computer and use it in GitHub Desktop.
【Python】CSVファイルの数字が正しくソートされないときの対処法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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