w3resource

Python File I/O: Read a file line by line store it into an array


7. File to Array

Write a Python program to read a file line by line store it into an array.

Sample Solution:-

Python Code:

def file_read(fname):
        content_array = []
        with open(fname) as f:
                #Content_list is the list that contains the read lines.     
                for line in f:
                        content_array.append(line)
                print(content_array)

file_read('test.txt')

Sample Output:

['Welcome to w3resource.com.\n', 'Append this text.Append this text.Append this text.\n', 'Append this text.\n
', 'Append this text.\n', 'Append this text.\n', 'Append this text.\n']  

Flowchart:

Flowchart: File I/O: Read a file line by line store it into an array.

For more Practice: Solve these Related Problems:

  • Write a Python program to read a file line by line into an array and then print the array’s elements in reverse order.
  • Write a Python program to read a file into an array and remove any duplicate lines before displaying the result.
  • Write a Python program to read a file into an array and sort the elements numerically if the lines represent numbers.
  • Write a Python program to read a file into an array and then count the frequency of each unique line.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to read a file line by line store it into a variable.
Next: Write a python program to find the longest words.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.