1
0

More than 1 year has passed since last update.

Python3でCGIチャレンジ2 ファイル書き込み

Last updated at Posted at 2021-12-03

前提

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

ブラウザで確認

[http://localhost:8000]

結果

入力して送信
image.png

作成されたファイルを開く
image.png

再度適当な入力して追記確認。
image.png

理解したこと

  • ファイルモード
  • エンコーディング指定。Python2とは記述が異なる。

情報源

Googleで「Python3 ファイル書き込み」で上から順に試した。

1
0
0

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