2011-07-16 33 views

答えて

3
print "\nReading the entire file into a list." 
text_file = open("read_it.txt", "r") 
lines = text_file.readlines() 
print lines 
print len(lines) 
for line in lines: 
    print line 
text_file.close() 
+1

実際にはここで2回反復する必要はありません。最初はreadlinesを使用し、2回目はforループを使用します –

0

または:あなたがファイルを閉じるについてはこちらを気にする必要はありませんし、またここにreadlinesを使用する必要がない

allRows = [] # in case you need to store it 
with open(filename, 'r') as f: 
    for row in f: 
     # do something with row 
     # And/Or 
     allRows.append(row) 

注意。

5

シンプル:

with open(path) as f: 
    myList = list(f) 

あなたは改行をしたくない場合は、あなたがlist(f.read().splitlines())

1

Maxの答えは動作します行うことができますが、あなたがでendline文字(\n)が残されます各行の終わり。

ことが望ましい振る舞いでない限り、次のパラダイムを使用します。あなたは、Pythonを学ぶために使用しているどのようなチュートリアル

with open(filepath) as f: 
    lines = f.read().splitlines() 

for line in lines: 
    print line # Won't have '\n' at the end 
関連する問題