【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