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

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

Sponsored Link

テキストファイルへの書き込み処理を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

Comments:0

Comment Form
Remember personal info

Trackbacks:0

Trackback URL for this entry
http://www.yukun.info/blog/2008/09/python-file-write-writelines.html/trackback
Listed below are links to weblogs that reference
Python: テキストファイルに書き込み - write()、writelines()メソッド from Yukun's Blog

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

バックナンバー
最近のコメント
最近のトラックバック
メタ情報

Return to page top