2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Windowsのソートを実装する(Python,Windows)

Posted at

ファイル操作をするとき

順番に操作したいときがあるときがあります。当然ソートするわけですが、このソート順は必ずしも一致しません。

natsortとか

0.txt
1.txt
2.txt
10.txt
15.txt

このようなファイルをソートすると、通常のソートでは文字コード基準になり

0.txt
1.txt
10.txt
15.txt
2.txt

こうなります。最初のように数字順に並べるのがnatsortです。Pypiにあります。

それでも困ることがある

Windowsのエクスプローラは、Windows7からこのような自然なソートをします。するのですが、これが困ったことに数字以外の記号や漢字はnatsortと微妙に違うソート順でソートされます。たまに困ります。

なので

Windowsのエクスプローラと全く同じ結果を出すソートが必要です。多分
もちろん、Windowsでしか動く必要がないので、Windows専用です。

winsort.py
def winsort(lst):
    import ctypes
    from functools import cmp_to_key

    SHLWAPI = ctypes.windll.LoadLibrary("SHLWAPI.dll")
    def cmpstr(a, b):
        return SHLWAPI.StrCmpLogicalW(a, b)

    return sorted(lst, key=cmp_to_key(cmpstr))

なんか普通に5ちゃんねるの超初心者スレにあったよこれ

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?