LoginSignup
0
2

More than 1 year has passed since last update.

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

Last updated at Posted at 2020-08-04

今回の内容

Pythonスクリプトで自分がよく使うフレーズのメモです。
不定期に更新予定。内容が変わる可能性あり。

拡張子なしのファイル名を取得

[追記:2021-12-21]
拡張子も使うことが多いので、ファイル名と拡張子を取得。こっちのがわかりやすい。

import os
basename,ext = os.path.splitext(os.path.basename(filepath))

コマンドライン引数(追記:2021-12-21)

【参考文献】ArgumentParserの使い方を簡単にまとめた
自分なりに使うものを抽出した。

import argparse

def get_args():
    parser = argparse.ArgumentParser('スクリプト説明')
    parser.add_argument('argv', nargs='*', help='引数の説明。必須引数')
    parser.add_argument('-a','--aaa',default='hogehoge', help='ヘルプ')
    parser.add_argument('-b','--bbb',action='store_true')
    return parser.parse_args()

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

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

main()

スクリプトのあるディレクトリパスの取得(追記:2022-02-08)

スクリプトファイルを起点とした相対パス指定などに使う。

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

ホームディレクトリ取得(追記:2022-05-31)

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

テキスト読込・書き込み(追記:2022-05-31)

## テキストファイル読み込み
with open('text_file') as f:
    text = f.read()
    text_l = [s.strip() for s in f.readlines()]

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

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

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').read(1024))
    if result:
        return False
    else:
        return True

外部コマンド実行

import subprocess

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

## 出力をテキストとしてしゅとく
output = subprocess.run(cmd, shell=True capture_output=True, text=True).stdout

ディレクトリ名、ファイル名、拡張子の取得

import pathlib

p_file = pathlib.Path(file)
dirname = p_file.parent
name = p_file.stem
ext = p_file.suffix.lstrip('.')

一時ディレクトリ

import tempfile

with tempfile.TemporaryDirectory() as dname:

タイムスタンプ取得(追記:2021-12-21)

import datetime
dt = datetime.datetime.now()
timestamp = dt.strftime('%Y-%m-%d')
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