ファイルへ書き込むにはwrite関数やwritelines関数を使用します。
write関数でファイルに書き込みをする
write関数の書式は以下の通りです。
1 |
対象のファイルオブジェクト.write(書き込む文字列) |
write関数を使用したサンプル
ファイルを開くのにはopen関数を利用します。書き込みの場合は第2引数に「'w'」を渡してファイルを書き込みモードで開いておくのを忘れないようにしてください。
1 2 3 4 5 6 7 8 9 |
# -*- coding: utf-8 -*- # 書き込む文字列 text = "The quick brown fox jumps over the lazy dog." # ファイルを書き込みモードで開く with open('sample.txt', 'w') as f: # 書き込み f.write(text) |
sample.txtの中身を確認するとtext変数の文字列が書き込まれていることが確認できます。
1 2 |
$ cat sample.txt The quick brown fox jumps over the lazy dog. |
writelines関数で配列の文字列をファイルに書き込む
writelines関数では配列を引数に渡すと、配列内の文字列をファイルに書き込むことができます。使い方はwrite関数とほぼ同じです。
writelines関数の書式は以下の通りです。
1 |
対象のファイルオブジェクト.writelines(書き込む文字列の配列) |
writelines関数を使用したサンプル
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# -*- coding: utf-8 -*- # 書き込む文字列の配列 text = [ "Shall I compare thee to a summer's day? ", "Thou art more lovely and more temperate. ", "Rough winds do shake the darling buds of May, ", "And summer's lease hath all too short a date. ", "Sometime too hot the eye of heaven shines, ", "And often is his gold complexion dimm'd; ", "And every fair from fair sometime declines, ", "By chance or nature's changing course untrimm'd; ", "But thy eternal summer shall not fade", "Nor lose possession of that fair thou owest; ", "Nor shall Death brag thou wander'st in his shade, ", "When in eternal lines to time thou growest: ", "So long as men can breathe or eyes can see, ", "So long lives this and this gives life to thee." ] # ファイルを書き込みモードで開く with open('sample.txt', 'w') as f: # 書き込み f.writelines(text) |
sample.txtの中身を確認するとtext変数の配列の中身が書き込まれていることが確認できます。
1 2 |
$ cat sample.txt Shall I compare thee to a summer's day? Thou art more lovely and more temperate. Rough winds do shake the darling buds of May, And summer's lease hath all too short a date. Sometime too hot the eye of heaven shines, And often is his gold complexion dimm'd; And every fair from fair sometime declines, By chance or nature's changing course untrimm'd; But thy eternal summer shall not fadeNor lose possession of that fair thou owest; Nor shall Death brag thou wander'st in his shade, When in eternal lines to time thou growest: So long as men can breathe or eyes can see, So long lives this and this gives life to thee. |