Python: テキストファイルに書き込み – write()、writelines()メソッド

Sponsored Link

このエントリーをはてなブックマークに追加
はてなブックマーク - Python: テキストファイルに書き込み – write()、writelines()メソッド
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Livedoor Clip
Bookmark this on Yahoo Bookmark

テキストファイルへの書き込み処理をFileオブジェクトの以下のメソッドを用いて書いてみます。

  • write() – 文字列を引数に取り、ファイルに書き込む。
  • writelines() – シーケンス型を引数に取り、ファイルに書き込む。

write() – 文字列を引数に取り、ファイルに書き込む

ソースコード

#!/usr/bin/python
# coding: UTF-8

# 書き込む文字列
str = """It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on."""

f = open('text.txt', 'w') # 書き込みモードで開く
f.write(str) # 引数の文字列をファイルに書き込む
f.close() # ファイルを閉じる

実行結果

text.txt

It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.

writelines() – シーケンス型を引数に取り、ファイルに書き込む

ソースコード

#!/usr/bin/python
# coding: UTF-8

str = """It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on."""
strs = str.split('n') # 一行が一要素(文字列)のリスト

f = open('text.txt', 'w') # 書き込みモードで開く
f.writelines(strs) # シーケンスが引数。
f.close()

実行結果

text.txt

It is meaningless only to think my long further aims idly.It is important to set my aims but at the same time I should confirm my present condition.Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.

書き込む際は、シーケンスの各要素の文字列を単に連結するだけです。間には改行も空白文字も含まれません。

そういえば、csv.writerオブジェクトを用いたCSVファイル書き込みにはlineterminatorオプション引数に、任意の連結文字列(言い方よくないね→行の終端文字)を代入できます。主に、環境に合わせた改行文字を代入するのに使います。→Python: CSVファイルに書き込み – csv.writerオブジェクト

リファレンス

関連すると思われる記事:

Sponsored Link

This entry was posted in Python and tagged , , . Bookmark the permalink.

Facebook comments:

コメントを残す

メールアドレスが公開されることはありません。

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>