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?
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With