0
2

More than 1 year has passed since last update.

【Python】Pythonスクリプトで自分がよく使うフレーズのメモ-2023

Last updated at Posted at 2023-03-29

今回の内容

Pythonスクリプトで自分がよく使うフレーズのメモを再度書き直しました。
番号を振っていますが、特に意味はなく順不同です。
勘違いや書き間違いがある可能性があります。気づいたことがありましたらコメントいただけると助かります。

【1】コマンドライン引数をリストとして取得

import sys
argv_list = sys.argv[1:]

【2】コマンドライン引数を扱う

【参考】
ArgumentParserの使い方を簡単にまとめた | Qiita
argparse --- コマンドラインオプション、引数、サブコマンドのパーサー | Python 3.11.2 documentation

import argparse

def get_args():
    parser = argparse.ArgumentParser('スクリプト説明')
    parser.add_argument('argv', nargs='*', help='引数の説明')
    parser.add_argument('-a','--aaa', help='サブ引数の説明')
    ## 引数に設定可能なオプション例
    # action='store_true' : その引数があればTrue、なければFalseを返す。
    # nargs='*' : 引数の数を指定。*は0個以上、+は1個以上。*や+のとき、値はリストとなる。
    # default='好きな値' : 引数を指定しなかったとき、この値になる。defaultのデフォルトはNone。
    # required = True : その引数を必須にする。
    # choices = ['選択肢1', '選択肢2']:指定可能な値を設定することができる。
    return parser.parse_args()

def main():
    args = get_args()
    argv_list = args.argv
    aaa = args.aaa

    ## 以下、何かしらの処理

main()

【3】スクリプトのあるディレクトリパスの取得

【参考】
Pythonで実行中のファイルの場所(パス)を取得する__file__ | note.nkmk.me

・os

import os
script_dir = os.path.dirname(os.path.abspath(__file__))

・pathlib

import pathlib
script_dir = pathlib.Path(__file__).resolve().parent

※参考までに、bashスクリプトの場合

script_dir=$(cd $(dirname $0) && pwd)

【4】ホームディレクトリ取得

【参考】
pythonでホームディレクトリの取得 | Qiita

import os
homedir = os.path.expanduser("~")

【5】ファイルパスの親ディレクトリ名、ファイル名、拡張子名

【参考】
Pythonでパス文字列からファイル名・フォルダ名・拡張子を取得、結合 | note.nkmk.me
Python, pathlibでファイル名・拡張子・親ディレクトリを取得 | note.nkmk.me

・os

import os

filepath = '/path/to/file.ext'

dirpath = os.path.dirname(filepath)
dirname = os.path.basename(os.path.dirname(filepath))
filename =  os.path.basename(filepath)
stem, ext = os.path.splitext(os.path.basename(filepath))

## results
# dirpath = '/path/to'
# dirname = 'to'
# filename = 'file.ext'
# stem = 'file'
# ext = '.ext'

・pathlib

import pathlib

filepath = '/path/to/file.ext'

p_file = pathlib.Path(filepath).resolve()
dirpath = p_file.parent
dirname = p_file.parent.name
filename = p_file.name
stem = p_file.stem
ext = p_file.suffix.lstrip('.')

## results
# dirpath = '/path/to'
# dirname = 'to'
# filename = 'file.ext'
# stem = 'file'
# ext = 'ext'

【6】外部コマンド実行

【参考】
pythonのsubprocessで標準出力を文字列として受け取る | Qiita

import subprocess

cmd = "コマンド"
proc = subprocess.run(cmd, shell=True)

## 出力をテキストとして取得
proc = subprocess.run(cmd, shell=True, capture_output=True, text=True)
result = proc.stdout

【7】日付を文字列として取得

【参考】
Pythonで日付から曜日や月を文字列(日本語や英語など)で取得 | note.nkmk.me

import datetime
dt = datetime.datetime.now()
timestamp = dt.strftime('%Y-%m-%d')

## それぞれ取得
year = datetime.datetime.now().year
month = datetime.datetime.now().month
today = datetime.datetime.now().day

【8】テキストファイルかどうか判定

【参考】
How can I detect if a file is binary (non-text) in Python? - Stack Overflow

def is_text_file(file):
    def is_binary_string(Bytes):
        textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
        result = bool(Bytes.translate(None, textchars))
        return result
    result = is_binary_string(open(file, 'rb').r\ead(1024))
    if result:
        return False
    else:
        return True

【9】テキスト読込・書き込み

【参考】
Pythonでファイルの読み込み、書き込み(作成・追記) | note.nkmk.me

## テキストファイル読み込み
text_file = "/path/to/file"

with open(text_file) as f:
    text = f.read()

## テキストファイルをリストとして読み込み
with open(text_file) as f:
    text_l = [s.strip() for s in f.readlines()]

## テキストファイル書き込み
with open(text_file, mode='w') as f:
    f.write('文字列')

【10】一時ディレクトリ

【参考】
Pythonで一時ディレクトリを作って安全に後始末する | Qiita

import tempfile

with tempfile.TemporaryDirectory() as dname:

【11】パスが存在するかどうか確認

【参考】
Pythonでファイル、ディレクトリ(フォルダ)の存在確認 | note.nkmk.me

import os
os.path.exists(filepath)
0
2
2

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
0
2