- 2008-09-06 (土) 21:50
- Python
テキストファイルへの書き込み処理を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オブジェクト
リファレンス
関連記事
- AIR: テキストファイルに書き込み - openAsync()、writeMultiByte()
- Python: CSVファイルに書き込み - csv.writerオブジェクト
- Python: テキストファイルの読み込み - read()、readlines()、readline()メソッド
- Python: テキストファイルの行頭に行番号を追加
- Python: コマンドライン引数の取得 - sys.argv変数
Sponsored Link
- Newer: Rで統計: ベクトル変数に対する操作 - 複数データを一括処理
- Older: SafariとChromeでSyntaxHighlighterのPythonコードがハイライトされない問題の解決法
Comments:0
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