How to Read a File into an Array in Python?

In this tutorial, I will explain how to read a file into an array in Python. Someone asked me this doubt during a Python webinar and this was the topic of discussion. So I decided to write an article on this. We will explore different methods to read a text file and store its contents in an array or list in Python.

Check out How to Initialize an Array in Python

Read a File into a Python Array

Let us see different ways to read a file into a Python array.

1. Use the open() Method

The most simple way to read a text file into a list in Python is by using the open() method. Here’s an example:

# Open the text file
with open('customers.txt', 'r') as file:
    # Read the contents of the file into a list
    customer_list = file.readlines()

# Print the list
print(customer_list)

In this example, we use the open() function to open the file named ‘customers.txt’ in read mode (‘r’). The with statement ensures that the file is properly closed after reading it. Inside the with block, we use the readlines() method to read all the lines of the file and store them in the customer_list variable. Each line in the file becomes an element in the list.

Read How to Multiply an Array by a Scalar in Python

2. Use the numpy.load txt() Function

If you’re working with numerical data, you can use the numpy library to efficiently read a text file into a NumPy array. Here’s an example:

import numpy as np

# Load data from the text file into a NumPy array
sales_data = np.loadtxt('sales.txt')

# Print the array
print(sales_data)
Read a File into an Array in Python

In this example, we import the numpy library and use the loadtxt() function to read the data from the ‘sales.txt’ file into a NumPy array called sales_data. The loadtxt() function automatically splits the data based on whitespace and converts it into a NumPy array.

Check out How to Find the Closest Value in an Array Using Python

3. Specify Delimiter and Data Type

You can also specify the delimiter and data type when using numpy.loadtxt():

import numpy as np

# Load data from the CSV file into a NumPy array
employee_data = np.loadtxt('employees.csv', delimiter=',', dtype=str)

# Print the array
print(employee_data)
How to Read a File into an Array in Python

In this example, we use the delimiter parameter to specify that the file is comma-separated (CSV) and the dtype parameter to indicate that the data should be loaded as strings.

Check out How to Remove Duplicates from a Sorted Array in Python

4. Read the File into a Python Array of Records

If your file contains structured data, such as records with multiple fields, you can read the file into an array of records. Here’s an example:

# Define the filename as a constant
DATA_FILE = 'students.csv'

def read_data_from_file():
    student_records = []
    with open(DATA_FILE, 'r') as file:
        for line in file:
            fields = line.strip().split(',')
            student_records.append(fields)
    return student_records

# Read data from the file
students = read_data_from_file()

# Print the array of records
for student in students:
    print(student)

In this example, we define a constant DATA_FILE to store the filename. We then create a function called read_data_from_file() that reads the data from the file into an array of records.

Inside the function, we open the file in read mode and iterate over each line. We use the strip() method to remove any whitespace and the split() method to split the line into fields based on the comma delimiter. Each set of fields represents a student record, which we append to the student_records list.

Finally, we call the read_data_from_file() function to read the data from the file and store it in the students variable. We then print each student record using a loop.

Read How to Iterate Through a 2D Array in Python

5. Use the CSV Module

Python provides a built-in csv module that simplifies reading and writing CSV files. Here’s an example of reading a CSV file into a list of lists using the csv module:

import csv

# Open the CSV file
with open('products.csv', 'r') as file:
    # Create a CSV reader object
    csv_reader = csv.reader(file)

    # Convert the CSV data into a list of lists
    product_data = list(csv_reader)

# Print the list of lists
for product in product_data:
    print(product)

In this example, we import the csv module and open the ‘products.csv’ file in read mode. We create a CSV reader object using csv.reader() and pass the file object to it.

We then convert the CSV data into a list of lists using the list() function and store it in the product_data variable. Each row in the CSV file becomes a sublist within the main list.

Check out How to Distinguish Between Arrays and Lists in Python

Conclusion

In this tutorial, we explored different methods to read a file into an array in Python. I explained open() method which is suitable for general text files, while the numpy.loadtxt() function is efficient for numerical data. If you have structured data or CSV files, you can use techniques like splitting fields or leveraging the csv module.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.