2023年12月5日火曜日

Python: 現在のディレクトリ取得と変更

現在のディレクトリを取得

import os

cwd = os.getcwd()

print(cwd)  # /Users/demo-user/documents/mydir


ディレクトリを変更

os.chdir('/Library')

cwd = os.getcwd()

print(cwd)  # /Library



2023年10月24日火曜日

.htaccess リダイレクト設定 ‐ ファイル名に半角スペースやカッコがある場合

Apacheサーバーにあるファイルのリダイレクト設定です。

ファイル名に半角スペースや半角カッコがあっため 500 Internal Server Errorが発生してディレクトリにアクセスできなくなってしまいます。

.htaccess 最初の設定 *このままだと500エラーが発生

RewriteEngine On
Rewriterule ^abc xyz.pdf$ https://example.com/abcxyz/ [L, R=301]
Rewriterule ^abc(123)xyz.pdf$ https://example.com/abcxyz/ [L, R=301]


ファイル名をクオーテーションマーク " で囲い(^と$の外側に記述)、半角カッコはバックスラッシュ \ でエスケープが必要でした。

.htaccess 修正後

RewriteEngine On
Rewriterule "^abc xyz.pdf$" https://example.com/abcxyz/ [L, R=301]
Rewriterule "^abc\(123\)xyz.pdf$" https://example.com/abcxyz/ [L, R=301]

2023年9月26日火曜日

正規表現で改行を含んだワイルドカード指定

([\s\S\n]*?) または ([\s\S\n]⁺?)

*は0個以上の一致、⁺は1個以上の一致

  • \s: 空白文字を表す。[ \t\n\r\f]と同じ
  • \S: 非空白文字を表す。[ \t\n\r\f]以外の一文字。
  • \n: 改行文字を表す。

参考: VS Codeで複数行に渡って正規表現を利用する - Qiita
https://qiita.com/birdwatcher/items/dee34a11619b11e1fe81

2023年9月22日金曜日

django-CMSでのチェック方法

django-CMS (https://www.django-cms.org)

$ python manage.py cms check

を実行すると保存されておらずorphanedになったものが発見される場合がある。
以下を実行して削除する。

$ python manage.py cms list plugins

$ python manage.py cms delete-orphaned-plugins


2023年8月10日木曜日

Python クロージャ―で文字列を連続して連結

Pythonでクロージャ―を使って文字列を連続して連結する方法です。
def add_string():
    string = ''
    def add_string_inner(new_string):
        nonlocal string
        string += new_string
        return string
    return add_string_inner
messages = add_string()

print(messages(''))     # 空白
print(messages('abc'))  # abc
print(messages('123'))  # abc123
print(messages('xyz'))  # abc123xyz

2023年8月3日木曜日

Python テキストファイルを1行ずつ読み込み処理する readlines と readline メソッド

readlines() ... テキストファイル内容を一気に読み込み、1行ずつリストにします。ファイルサイズがよほど大きくなければ通常はこれを使います。

readline() ... テキストファイルを1行ずつ読み込みます。すべての行に対する処理は少し工夫が要ります。

以下、TEST.txt の内容が、

あいうえお[改行]
[改行]
かきくけこ[改行]
さしすせそ

というものとします。

2023年8月2日水曜日

Youtube サムネイル画像の取得

Youtube動画URL
https://www.youtube.com/watch?v=動画ID


120 × 90 [default]
http://img.youtube.com/vi/動画ID/default.jpg

120 × 90 [ 1 ]
http://img.youtube.com/vi/動画ID/1.jpg

120 × 90 [ 2 ]
http://img.youtube.com/vi/動画ID/2.jpg

120 × 90 [ 3 ]
http://img.youtube.com/vi/動画ID/3.jpg

320 × 180
http://img.youtube.com/vi/動画ID/mqdefault.jpg

480 × 360
http://img.youtube.com/vi/動画ID/hqdefault.jpg

640 × 480
http://img.youtube.com/vi/動画ID/sddefault.jpg

1280 × 720
http://img.youtube.com/vi/動画ID/maxresdefault.jpg