2009年10月14日水曜日

ファイル入出力

改行をbrタグに置換
open("index.html", "w").write(open("index.txt").read().replace("\n","<br>\n"))

HTMLエンコード
html = open("index.txt").read()
html = html.replace('&','&amp;')
html = html.replace('<','&lt;')
html = html.replace('>','&gt;')
html = html.replace('"','&quot;')
open("index.html","w").write(html)
※&のエンコードを最初にしないとうまくいきません。

HTML一括生成
HTMLテンプレートと設定CSVから一括でHTMLを生成
HTMLテンプレート例
<html>
<head><title>[[title]]</title></head>
<body>
<h1>[[title]]</h1>
<p>[[contents]]</p>
</body>
</html>
CSV例
page1.html,page1,This is page one!
page2.html,page2,This is page two!
page3.html,page3,This is page three!
page4.html,page4,This is page four!
ソースコード
>>> for line in open("contents.csv"):
...     filename,title,contents = line.split(",")
...     open(filename,"w").write(open("template").read().replace("[[title]]",title
).replace("[[contents]]",contents))

1行目で、CSVを読み込み1行ずつループを実行
2行目で、CSVをカンマで分割し変数に代入
3行目で、テンプレートを開き、該当箇所を置換した後、保存

0 件のコメント:

コメントを投稿