ディレクトリ / ファイル
パス / 拡張子
ディレクトリの作成
# ディレクトリの作成 os.makedirs(path)
拡張子の取得
# 拡張子を小文字で取得 extension = os.path.splitext(path)[1].lower()
.lower()
で強制的に小文字に変換
拡張子抜きのファイル名
# 拡張子抜きのファイル名 file_name_without_extension = os.path.splitext(os.path.basename(filePath))[0]
import os path = 'C:\\hoge\\fuga.exe' file_name_without_extension = os.path.splitext(path) print(file_name_without_extension) #-> ('C:\\hoge\\fuga', '.exe')
ファイル名とフォルダ名のペアを取得
path_info = os.path.split() dir_path = path_info [0] file_name = path_info [1]
相対パスで上の階層を取得する
path = os.path.abspath(os.path.join(file_path, "../../../../../"))
ディレクトリを丸ごと削除
shutil.rmtree(dir_path)
ファイルを削除
os.remove(file_path)
ファイル / ディレクトリの移動
# ファイルの移動 ※ 同名ファイルが移動先に存在するとエラー shutil.move(old_file_path, new_dir_path) # ファイルの移動 ※ 同名ファイルがあれば強制的に上書き shutil.move(old_file_path, new_file_path) # ディレクトリの移動 shutil.move(old_dir_path, new_dir_path)
ディレクトリを開く
# 開く subprocess.run(['explorer', path]) # 開いて選択 subprocess.run(['explorer', '/select,', path])
実行しているファイルのパスを取得
launch_file_path = __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
日時の取得
now = datetime.datetime.now() date_time = now.strftime('%Y-%m-%d %H:%M:%S')
ファイルの読み込み
エンコードに合わせて読み込む
with open(file_path, 'rb') as f: data = f.read() result = chardet.detect(data) encoding = result['encoding'] with open(file_path, encoding=encoding) as f: contents = f.read()
glob モジュール
標準ライブラリのためインストール不要。
条件を満たすファイル名やディレクトリ名などのパスの一覧を取得する。
ワイルドカード検索
import glob # test 階層にある全ての png データのファイルパスがリストに格納される png_list_1 = glob.glob('test/*.png') print(png_list_1) #-> ['test\\00000.png', 'test\\00001.png', 'test\\00002.png', 'test\\00003.png', 'test\\00004.png', 'test\\00005.png'] # 0 から始まって 5 で終わる png ファイル png_list_2 = glob.glob('test/0*5.png') print(png_list_2) #-> ['test\\00005.png']
特定の文字で検索
import glob # ? # ファイル名が 3文字の png ファイル png_list_1 = glob.glob('test/???.png') print(png_list_1) # [0-9] # 2桁の数字名のファイルで 1桁目が 4以下 png_list_2 = glob.glob('test/[0-9][0-4].png') print(png_list_2) # [a-z] # 3文字の英字名のファイル png_list_3= glob.glob('test/[a-z][a-z][a-z].png') print(png_list_3)
サブディレクトリも検索 | recursive
recursive=True
を渡すことで**
の部分でサブディレクトリも検索するようになる。
※ Python 3.5 以降
import glob # test 階層以下にあるサブディレクトリを含めた # 全ての png データのファイルパスがリストに格納される png_list = glob.glob('test/**/*.png', recursive=True) print(png_list)
ファイルの実行
.lnk ファイルの元を取得
pip install pywin32
import win32com.client wshell = win32com.client.Dispatch("WScript.Shell") shortcut = wshell.CreateShortcut(item_path) item_path = shortcut.TargetPath
既定のプログラムでファイルを実行
subprocess.Popen(['start', item_path], shell=True)
exe ファイルの実行
subprocess.run(item_path)
ダブルクリックでファイルを実行する
''' ダブルクリック -------------------------------------------------------------------------------------------------------------------- ''' def double_clicked(self): path = self.path_Line.text() item = self.item_listWidget.selectedItems()[0].text() item_path = path + '\\' + item # 実行したのがファイルの場合 # ============================================================================================================== if os.path.isfile(item_path): extention = os.path.splitext(item_path)[1].lower() if not extention in settings.RELIANCE_FILES: # ショートカットファイルの場合はリンク元のパスを取得 # ------------------------------------------------------------------------------------------------------ if extention == '.lnk': if settings.ENVIRONMENT == 'standalone': wshell = win32com.client.Dispatch("WScript.Shell") #<COMObject WScript.Shell> shortcut = wshell.CreateShortcut(item_path) item_path = shortcut.TargetPath extention = os.path.splitext(item_path)[1].lower() else: return # exe ファイルの場合 # ------------------------------------------------------------------------------------------------------ if extention == '.exe': subprocess.run(item_path) else: subprocess.Popen(['start', item_path], shell=True)
ロガー
ロガーの設定
# ロガーのレベルを取得する self.logger_level = logging.getLevelName(self.logger.level)
インストール済みパッケージの共有
インストール済みパッケージをファイル化
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)]
文字コード
ファイルの文字コードを取得
import chardet with open(csv_file_path, 'rb') as f: binary_file = f.read() _encode = chardet.detect(binary_file) encode = _encode['encoding'] print(_encode) print(encode)
{'encoding': 'SHIFT_JIS', 'confidence': 0.7785388127853882, 'language': 'Japanese'} SHIFT_JIS