0
0

More than 1 year has passed since last update.

文言を出力する際""で囲まれないようにする方法

Last updated at Posted at 2023-03-07

実行環境と結論

Windows環境、Pythonのwith open関数を使ったテキストファイル出力について。
簡単な処理ログを出力しようとした際、文言に空白があると""で囲まれ見栄えが悪かったので囲まれない方法を調べた。

結論としては「 」をセパレータとしてCSV出力する際、半角スペース「' '」をノンブレーキングスペース「\uA00」で置換するだけ。
csvモジュールを使わずとも「print(_message, sep=' ', file=f)」で簡潔に実現可能。
(コメントありがとうございます!)

ソースコードと実行例

print_log関数の引数として渡した文言をログに追記していくという処理。
ファイル名や出力先の設定、関数の呼び出し日時も出力文言に含める処理などは割愛。

sample.py
def print_log(_message):
    _log_file_name = 'MM-dd.log'
    with open(_log_file_name, 'a', newline='', encoding='utf-8') as f:
        print(_message, sep=' ', file=f)
実行例.py
count_now = 1
count_all = 10000
s = f'{count_now:>6} / {count_all:>6} 件完了'

print_log(s)

出力結果は以下のとおり。期待どおり文字寄せの空白があっても
「""」で囲まれるようなことはなく出力できた。
image.png

以上、備忘のため残す。

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