前提
Python3でCGIチャレンジ1後
作業フォルダ
ps1
作業
sample.pyを修正。
sample.py
import cgi
import cgitb
cgitb.enable()
print("Content-Type: text/html")
print()
form = cgi.FieldStorage()
f = open('file.txt', 'a', encoding='UTF-8') # add
for key in form:
value = form[key].value
print('<p>%s: %s</p>' % (key, value))
f.write('%s: %s, ' % (key, value)) # add
f.write('\n') # add
f.close() # add
ターミナルでコマンド実行して、ローカルでCGIサーバーを起動する。
python -m http.server --cgi 8000
ブラウザで確認
結果
理解したこと
- ファイルモード
- エンコーディング指定。Python2とは記述が異なる。
情報源
Googleで「Python3 ファイル書き込み」で上から順に試した。