幻魔ナイトブログ

主に絵、音楽、プログラミングなどについて書きます。

Pythonでファイルの文字列をデコードする。(Quated-pritableを読めるようにする)

f:id:MahiroN:20200823135552p:plain

最近会社で文字列でコード処理を書く必要があったので軽くメモとして残しておきます。

よくあるシチュエーションですが、保守対応でエンコード後のファイイルだけが資料として存在しているためデコードして読めるようにする必要があるという物です。

以下のコードでquoted-pritableを可読なものに変更します。

import sys
import quopri
args=sys.argv

inputfile = args[1]
outputfile = args[2]

# ファイル読み込み
with open(inputfile, 'r', encoding='utf-8') as f:

#with open(inputfile, 'b') as f:
    data = f.read()  

# 変換
pre_decoded = quopri.decodestring(data,header=False)
decoded = pre_decoded.decode("utf-8", "ignore")

# 出力
with open(outputfile, 'w', encoding='utf-8') as fo:
    fo.write(decoded)

お問合わせはこちら