- 2008-06-09 (月) 0:00
- Python
以下の読み込み用テキストファイルを用いて、
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.
以下のメソッドを用いた場合の処理を書いてみます。
- read() - ファイルを全て読み込み、その文字列データに対して処理を行う
- readlines() - ファイルを全て読み込み、1行毎に処理を行う
- readline() - 1行毎に読み込み、その処理を繰り返す
read() - ファイルを全て読み込み、その文字列データに対して処理を行う
#!/usr/bin/python
# coding: UTF-8
f = open('text.txt')
data1 = f.read() # ファイル終端まで全て読んだデータを返す
f.close()
print type(data1) # 文字列データ
lines1 = data1.split('n') # 改行で区切る(改行文字そのものは戻り値のデータには含まれない)
print type(lines1)
for line in lines1:
print line
print
実行結果
<type 'str'> <type 'list'> 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.
readlines() - ファイルを全て読み込み、1行毎に処理を行う
#!/usr/bin/python
# coding: UTF-8
f = open('text.txt')
lines2 = f.readlines() # 1行毎にファイル終端まで全て読む(改行文字も含まれる)
f.close()
# lines2: リスト。要素は1行の文字列データ
for line in lines2:
print line,
print
実行結果
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.
readline() - 1行毎に読み込み、その処理を繰り返す
#!/usr/bin/python
# coding: UTF-8
f = open('text.txt')
line = f.readline() # 1行を文字列として読み込む(改行文字も含まれる)
while line:
print line
line = f.readline()
f.close
実行結果
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 Ishould do from now on.
リファレンス
チュートリアル
関連記事
- Python: CSVファイルの読み込み - csv.readerオブジェクト
- Python: テキストファイルの行頭に行番号を追加
- Python: コマンドライン引数の取得 - sys.argv変数
- Python: テキストファイルに書き込み - write()、writelines()メソッド
- AIR: テキストファイルを非同期に読み込む - openAsync()、readMultiByte()
Sponsored Link
- Newer: Python: 乱数の生成 - random()、randint()、uniform()、seed()メソッド
- Older: Python: 現在の日付・時刻の取得と出力 - datetimeクラスの属性、today()、strftime()メソッド
Comments:0
Trackbacks:0
- Trackback URL for this entry
- http://www.yukun.info/blog/2008/06/python-file.html/trackback
- Listed below are links to weblogs that reference
- Python: テキストファイルの読み込み - read()、readlines()、readline()メソッド from Yukun's Blog