26

So in Ruby I can do the following:

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

How would one do that in Python?

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
walterfaye
  • 819
  • 2
  • 9
  • 15

3 Answers3

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

This is possible because Python allows you to iterate over the file directly.

Alternatively, the more straightforward method, using f.readlines():

with open('topsites.txt') as my_file:
    testsite_array = my_file.readlines()
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
11

Just open the file and use the readlines() function:

with open('topsites.txt') as file:
    array = file.readlines()
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
7

In python you can use the readlines method of a file object.

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

or simply use list, this is same as using readlines but the only difference is that we can pass an optional size argument to readlines :

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

help on 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.
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504