Bus errorとSegmentation faultに困ったら見るブログ

物理の研究者による日々の研究生活のメモ書きです ( python/emacs/html/Japascript/シェルスクリプト/TeX/Mac/C言語/Linux/git/tmux/R/ポケモンGO)

【python3】os.listdir()でlsをしたら、sortしないと順番が適当 + ファイル名のみを取り出す + lsでワイルドカードを使いたい

■ 参考 : pythonのosライブラリのos.listdir()で格納したファイル名の順番の仕組みがわからない。

import os

hoge = os.listdir("./")
print(hoge)

とかすると、hogeの中身の順番がめちゃくちゃ・・・
なのでソートする必要がある
import os

hoge = os.listdir("./")
hoge = sorted(hoge)
print(hoge)



■ 参考 : Pythonでファイル名・ディレクトリ名の一覧をリストで取得

# pathにディレクトリ名を入れる
files = os.listdir(path)
files = sorted(files)
hoge = [f for f in files if os.path.isfile(os.path.join(path, f))]
hoge = sorted(hoge)


ワイルドカードを使ったlsをしたい

globを使えば良い

■ 参考 : Pythonでフォルダ内のファイルリストを取得する

import glob
ls_result = glob.glob("./*.txt")


ファイル名から拡張子を消したいとき

filename_no_extension = os.path.splitext(filename)[0]

ランキング参加中です

↓クリックしていただけると嬉しいです〜