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