Saturday, 28 April 2018

Reading a file line by line into elements of an array in Python




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?


Answer



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()

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...