2013-04-25 6 views
8

में एक सरणी के तत्वों में लाइन द्वारा एक फ़ाइल लाइन पढ़ना तो रूबी में मैं क्या कर सकते हैं निम्नलिखित:अजगर

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

एक कैसे करना होगा कि अजगर में?

उत्तर

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

यह संभव है क्योंकि अजगर आप सीधे फ़ाइल पर चीज़ों को दोहरा सकते।

वैकल्पिक रूप से, और अधिक सरल विधि, 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.