LoginSignup
2
0

More than 5 years have passed since last update.

txtファイルを書き換える

Last updated at Posted at 2018-01-20

txtの書き換え

とあるホームページを作るために記事を募集しまして、そのtxtファイルをhtmlに載せられるように書き換えるプログラムを書いてみました。

テキストファイル

title

text
with open ('sample.txt', 'r', encoding='utf8') as input:
    txt1 = (input.readline())
    txt2 = (input.readlines())
    y = []
    print(txt2)
    x = ["<!DOCTYPE html>\n     <html>\n      <head>\n        <link rel=\"stylesheet\" href=\"../css/sample.css\">\n        <meta charset=\"utf-8\">\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n        <title>sample</title>\n      </head>\n      <body>\n        <div id=\"wrap\">\n          <h1 id=\"title\">\" ", txt1 ,    "</h1>\n      <p id = \"p\"> )"    ,txt2, "<\p>\n     </div>\n     </body>\n    </html>"]

    y = " ".join(map(str,x))

f = open('sample.txt', 'w', encoding='utf8')
f.write(y)
f.close()

とまあ、シンプルです。
ちゃんと動くのでokです。
まあこんな感じのを作りました。
別に問題点はないですが、わからないことが2個。。。

わからなかった点

  • 何がわからなかったかというと一つ目はxのリストを作ったのはいいが、リストは横に間延びして見にくい。そして、わざわざ一つ一つに\nを入れていかないと改行にならないのでめんどくささがあった。
  • 1つめはwithでのファイルインポートの仕方がwriteのときにどのようにやればよいのかわからなかった。
with open ('sample.txt', 'w', encoding='utf-8')
    write(y)

だと何を書くのか指定できない。。。

おわりに

これで仕事が少し減るのでハッピーです。やっぱりプログラミングは効率的で最高。
書き出すときのwithでの記述の仕方をご存知でしたらコメント頂けると幸いです。

2
0
2

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