2013-04-25 79 views

回答

12
testsite_array = [] 
with open('topsites.txt') as my_file: 
    for line in my_file: 
     testsite_array.append(line) 

這是可能的,因爲Python允許您直接遍歷文件。

或者,更簡單的方法,使用f.readlines()

with open('topsites.txt') as my_file: 
    testsite_array = my_file.readlines() 
5

只要打開該文件,並使用readlines()功能:

with open('topsites.txt') as file: 
    array = file.readlines() 
5

在蟒可以使用文件對象的readlines方法。

with open('topsites.txt') as f: 
    testsite_array=f.readlines() 

或者乾脆用list,這是一樣的使用readlines但唯一不同的是,我們可以通過一個可選的大小參數readlines

with open('topsites.txt') as f: 
    testsite_array=list(f) 

幫助上file.readlines

In [46]: file.readlines? 
Type:  method_descriptor 
String Form:<method 'readlines' of 'file' objects> 
Namespace: Python builtin 
Docstring: 
readlines([size]) -> list of strings, each a line from the file. 

Call readline() repeatedly and return a list of the lines so read. 
The optional size argument, if given, is an approximate bound on the 
total number of bytes in the lines returned.