2013-04-25 19 views
8

bir dizinin elemanları içine hattı ile bir dosya hattını Okuma aşağıdadır:Yani Ruby yapabileceğim Python

testsite_array = Array.new 
y=0 
File.open('topsites.txt').each do |line| 
testsite_array[y] = line 
y=y+1 
end 

İnsan nasıl Python bunu yapar?

cevap

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

bu mümkündür. f.readlines() kullanarak Alternatif

, daha anlaşılır yöntem: python'da

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

Sadece readlines() fonksiyonunu dosyasını açmak ve kullanımı: Python doğrudan dosyanın üzerine yineleme izin verdiğinden

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

bir dosya nesnesinin readlines yöntemi kullanabilirsiniz.

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

veya basitçe list kullanın bu readlines kullanarak aynıdır ancak tek fark, bizim readlines için isteğe bağlı boy argüman iletebilirsiniz şudur:

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

yardım file.readlines tarih:

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.