質問編集履歴
1
コード内容の修正
test
CHANGED
File without changes
|
test
CHANGED
@@ -6,7 +6,7 @@
|
|
6
6
|
1.csvファイルの 商品名(降順、昇順どちらでも可)で並び替え
|
7
7
|
2.価格で並び替え。(降順で並び替え)
|
8
8
|
|
9
|
-
ですが、pythonで並び替えようとすると、1つのキー列でしから並び替える方法がわからず困っております。
|
9
|
+
ですが、参考にしたpythonで並び替えようとすると、1つのキー列でしから並び替える方法がわからず困っております。
|
10
10
|
※書いたコードでは、商品名でしか並び替えれない状況です。
|
11
11
|
|
12
12
|
どなたか、【商品名】で並び替えた後に、【価格】で並び替える方法をお分かりの方がおられましたらご教示お願いできないでしょうか。
|
@@ -40,36 +40,22 @@
|
|
40
40
|
|
41
41
|
mailfile="mailfile.csv" #メール用の送信ファイル
|
42
42
|
|
43
|
-
# カレントディレクトリにtest.csvがあることを教える
|
44
43
|
current_path = os.path.dirname(__file__)
|
45
44
|
csv_file = pathlib.Path(current_path, mailfile)
|
46
45
|
|
46
|
+
def sort_csv(csv_file: pathlib, sort_row: int, desc: bool = False):
|
47
47
|
|
48
|
-
# sort_rowで指定した列を並び替える関数
|
49
|
-
def sort_csv(csv_file: pathlib, sort_row: int, desc: bool = False):
|
50
|
-
'''
|
51
|
-
第一引数:編集するCSVファイルをフルパスで指定
|
52
|
-
第二引数:ソートする列を数字で指定(左から0,1,2・・・)
|
53
|
-
第三引数:昇順(False)降順(True)を指定
|
54
|
-
'''
|
55
|
-
# 今回作成したuser_list_csvを開く
|
56
48
|
csv_data = csv.reader(open(csv_file), delimiter=',')
|
57
|
-
# ヘッダー情報を取得
|
58
49
|
header = next(csv_data)
|
59
|
-
# ヘッダー以外の列を並び替える
|
60
50
|
sort_result = sorted(csv_data, reverse=desc, key=operator.itemgetter(sort_row))
|
61
51
|
|
62
|
-
# 新規ファイルとしてuser_list_csvを開く
|
63
52
|
with open(csv_file, "w") as f:
|
64
|
-
# ヘッダーと並び替え結果をファイルに書き込む
|
65
53
|
data = csv.writer(f, delimiter=',')
|
66
54
|
data.writerow(header)
|
67
55
|
for r in sort_result:
|
68
56
|
data.writerow(r)
|
69
57
|
|
70
|
-
|
71
58
|
if __name__ == '__main__':
|
72
|
-
# csvをソートする関数を実行
|
73
59
|
sort_csv(csv_file, 2, False)
|
74
60
|
```
|
75
61
|
|