よく使う python コード集
インストール済みパッケージの共有
インストール済みパッケージをファイル化
pip freeze > requirements.txt
インストールしているモジュールがリスト化された requirements.txt ファイルが生成される。
文字列処理
末尾の削除 | .rstrip
a = "ABC-AB" b = a.rstrip("AB") print(b) # ABC-
前頭一致 | .startswith
rtn = 'python'.startswith('p') print(rtn)
末尾一致 | .endswith
rtn = 'python'.endswith('a') print(rtn)
文字列の中にで指定した文字列が存在するインデックスをすべて取得する
# 文字列の中に、指定した文字列が存在するインデックスをすべて取得する def get_index_list(self, targetText, str): index = -1 indes_list = [] while True: index = targetText.find(str, index + 1) if index == -1: break #print(index) indes_list.append(index) return indes_list
リスト処理
リストの重複を削除する | 二次元配列
# リストの重複を削除する def get_unique_list(seq): seen = [] return [x for x in seq if x not in seen and not seen.append(x)]
ディレクトリ / ファイル
拡張子の取得
extention = os.path.splitext(path)[1]
拡張子抜きのファイル名
fileName_withoutExtention = os.path.splitext(os.path.basename(filePath))[0] # 拡張子抜きのファイル名
ファイル名とフォルダ名のペアを取得
pathInfo = os.path.split() dirPath = pathInfo[0] fileName = pathInfo[1]
実行しているファイルのパスを取得する
launch_filePath = __file__
ユーザーディレクトリの取得
user_path = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH")
ディレクトリ内にあるすべての層のアイテムをリスト化
def get_all_itemList_indirectory(dirPath): found = [] for root, dirs, files in os.walk(dirPath): # ファイルを追加 #----------------------------------------------------------------------- for filename in files: found.append(os.path.join(root, filename)) # フォルダを追加 #----------------------------------------------------------------------- for dirname in dirs: found.append(os.path.join(root, dirname)) return found