2011-07-16 56 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

其實在這裏不需要迭代兩次 - 第一次使用readlines,第二次使用for循環 –

0

或者:

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) 

請注意,您不需要在這裏關心關閉文件,也沒有必要在這裏使用readlines方法。

5

簡單:

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

如果你不想換行,你可以做list(f.read().splitlines())

1

Max的回答會的工作,但你會留下在endline字符(\n)每一行的結尾。

除非這是期望的行爲,請使用以下模式:

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

for line in lines: 
    print line # Won't have '\n' at the end