0
0

More than 1 year has passed since last update.

Python3でCGIチャレンジ4 dictionary型でファイル読み書き

Posted at

作業フォルダ

ps4

作業

index.htmlの作成

index.html
<html>
<head><meta http-equiv="content-type" charset="UTF-8"></head>
<body>
  <form action="/cgi-bin/dictWrite.py" method="POST">
   入力1<input type="text" name="foo">
   入力2<input type="text" name="bar">
   <input type="submit">
  </form>

<!-- ここから追記 -->
  <form action="/cgi-bin/readFile.py" method="POST">
    <input type="submit" value="ファイル内容表示">
   </form>
<!-- ここまで追記 -->
</body>
</html>

cgi-binフォルダの作成

dictWrite.pyの作成。cgi-bin配下に作成。

dictWrite.py
import csv
import cgi
import cgitb
cgitb.enable()

print("Content-Type: text/html")
print()   

form = cgi.FieldStorage()

#辞書型の文字列作成
d = {'foo': form['foo'].value, 'bar': form['bar'].value}

with open('dict.csv', 'a', newline="", encoding='UTF-8')  as f:

  # 要素順の指定
  fieldnames = ['foo', 'bar']

  # writerオブジェクトを作成します.
  writer = csv.DictWriter(f, fieldnames=fieldnames, delimiter=",", quotechar='"')

  # writeheaderでヘッダー出力(追記なのでしない)
  # 新規のときだけ出力する条件は要調査
  # writer.writeheader()

  # writerowで1行分を出力します.
  writer.writerow(d)

print('書き込み完了')

readFile.py作成。cgi-bin配下に作成。

readFile.py
import csv
import cgi
import cgitb
cgitb.enable()

print("Content-Type: text/html")
print()   

# ファイルクローズが不要になる書き方
with open("dict.csv") as f:

  reader = csv.DictReader(f, delimiter=",", quotechar='"')

  for row in reader:
    print(row['foo'], row['bar'],'<br>')

ターミナルでコマンド実行して、ローカルでCGIサーバーを起動する。

python -m http.server --cgi 8000

ブラウザで確認

[http://localhost:8000]

結果

初期画面
image.png

入力して送信
image.png

ファイルの状況
image.png

ファイル内容表示ボタン
image.png

理解したこと

  • ファイルクローズが不要になるファイルの開き方
  • CSVパッケージの存在
  • CSVファイルの読み書き
  • dictionary型の取り扱い

情報源

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

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