Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 611
walterfaye Avatar asked Apr 25 '13 19:04

walterfaye


People also ask

How read a file line by line and store it in a array in Python?

Python read file line by line into arrayAn empty array is defined and the argument is opened as f and to read the line. The for line in f is used and to append the line into the array, array. append is used. The fruits file is passed as the parameter in the function.

How do I read a text file line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

How do you duplicate an array in Python?

To create a deep copy of an array in Python, use the array. copy() method. The array. copy() method does not take any argument because it is called on the original array and returns the deep copied array.


1 Answers

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() 
like image 183
Rushy Panchal Avatar answered Sep 19 '22 02:09

Rushy Panchal