LoginSignup
0
2

More than 3 years have passed since last update.

(自分用)Flask_5(txtファイルに追記する)

Posted at

項目

  1. txtファイルに追記する
  2. 閑話休題_txtファイルの任意の中身を削除、又は上書きする

1.txtファイルに追記する

html
<form action="/result" method="post">
        <label for="article">投稿</label>
        <input type="text" name="article">
        <p></p>
        <label for="name">名前</label>
        <input type="text" name="name">
        <button type="submit">送信する</button>
    </form>
  • これは前回もやった入力内容を送るコード
  • articlenameにそれぞれ保存している
python
article = request.form["article"]
name = request.form["name"]

file = codecs.open("articles.txt", "a", "utf-8")
file.write(article + "," + name + "\n")
file.close()
  • こいつを任意のルートに入れればOK
  • article = request.form["article"]name = request.form["name"]は前回やった通り、入力して保存されたデータを受け取っている
  • file = codecs.open("articles.txt", "a", "utf-8")"a"は追記するモードの事
  • .writeで書き込むよと宣言し、(article + "," + name + "\n"),で区切り、\nを入れる事で1行ごとに書き込まれる

2.閑話休題_txtファイルの任意の中身を削除、又は上書きする

  • .open()に入れる読み込みモードは、
  • rで読み込みのみモード
  • wで書き込みモード(これを使うと完全に上書きされて前のデータは削除される)
  • aで一番下に追記されるモード

がある。

hoge.txt
foobarfoobar

この様なtxtファイルがあった時、

python
open("hoge.txt","w").write(open("hoge.txt","r").read().replace("bar",""))

とする事で

hoge.txt
foofoo

と出来るのだ。

  • これはwで書き込む前に、rでtxtファイルの中身を参照しているから出来ているのである

3.終わりに

  • 正直最後のまだあんま理解してない
0
2
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
2