2013-04-25 10 views

Odpowiedz

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

Jest to możliwe, ponieważ Python umożliwia iteracyjne nad pliku bezpośrednio.

Alternatywnie sposób bardziej bezpośredni, przy użyciu f.readlines():

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

Wystarczy otworzyć plik i użyć funkcji readlines():

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

W python można użyć metody obiektu pliku readlines.

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

lub po prostu użyć list, to jest taki sam jak przy użyciu readlines ale jedyną różnicą jest to, że możemy przekazać opcjonalny rozmiar argumentu readlines:

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

Pomoc w 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. 
Powiązane problemy