NumPy File Handling Practice Questions with Solutions

Introductions

The NumPy File Handling module allows you to save, load, read, and write arrays efficiently. These functions are widely used in data science, machine learning, scientific computing, and automation projects where data needs to be stored and reused. In this chapter, you’ll practice beginner-friendly NumPy File Handling questions with complete solutions. NumPy File Handling practice questions with solutions help in understanding the concepts.


1. Python Program to Save a NumPy Array to a Binary File

Problem Statement

Write a Python program to save a NumPy array to a binary .npy file.

Python Solution

import numpy as np

numbers = np.array([10, 20, 30, 40, 50])

np.save("numbers.npy", numbers)

print("Array saved successfully.")

Sample Output

Array saved successfully.

Explanation

The np.save() function stores a NumPy array in a binary .npy file for fast loading later.

Concepts Covered

  • np.save()
  • .npy File Format

2. Python Program to Load a NumPy Array from a File

Problem Statement

Write a Python program to load a NumPy array from a .npy file.

Python Solution

import numpy as np

numbers = np.load("numbers.npy")

print(numbers)

Sample Output

[10 20 30 40 50]

Explanation

The np.load() function reads an array stored in a .npy file.

Concepts Covered

  • np.load()
  • Reading Binary Files

3. Python Program to Save Multiple Arrays in One File

Problem Statement

Write a Python program to save multiple NumPy arrays into a single .npz file.

Python Solution

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

np.savez("arrays.npz", first=a, second=b)

print("Arrays saved successfully.")

Sample Output

Arrays saved successfully.

Explanation

The np.savez() function stores multiple arrays in one compressed archive.

Concepts Covered

  • np.savez()
  • Multiple Arrays

4. Python Program to Load Multiple Arrays

Problem Statement

Write a Python program to load arrays from a .npz file.

Python Solution

import numpy as np

data = np.load("arrays.npz")

print(data["first"])
print(data["second"])

Sample Output

[1 2 3]
[4 5 6]

Explanation

Arrays are accessed using the names assigned while saving.

Concepts Covered

  • Loading .npz
  • Dictionary-like Access

5. Python Program to Save an Array as a CSV File

Problem Statement

Write a Python program to save a NumPy array to a CSV file.

Python Solution

import numpy as np

numbers = np.array([[10, 20],
                    [30, 40]])

np.savetxt("numbers.csv", numbers, delimiter=",", fmt="%d")

Sample Output

CSV file created successfully.

Explanation

The np.savetxt() function saves arrays in CSV or text format.

Concepts Covered

  • np.savetxt()
  • CSV Files

6. Python Program to Read a CSV File

Problem Statement

Write a Python program to read a CSV file using NumPy.

Python Solution

import numpy as np

numbers = np.loadtxt("numbers.csv", delimiter=",")

print(numbers)

Sample Output

[[10. 20.]
 [30. 40.]]

Explanation

The np.loadtxt() function loads data from CSV or text files.

Concepts Covered

  • np.loadtxt()
  • CSV Reading

7. Python Program to Save a Compressed File

Problem Statement

Write a Python program to save compressed NumPy arrays.

Python Solution

import numpy as np

numbers = np.array([10, 20, 30, 40])

np.savez_compressed("compressed.npz", data=numbers)

print("Compressed file saved.")

Sample Output

Compressed file saved.

Explanation

The np.savez_compressed() function reduces storage space by compressing arrays.

Concepts Covered

  • np.savez_compressed()
  • Compression

8. Python Program to Read a Text File

Problem Statement

Write a Python program to read a text file into a NumPy array.

Python Solution

import numpy as np

numbers = np.loadtxt("numbers.txt")

print(numbers)

Sample Output

[10. 20. 30. 40.]

Explanation

Text files containing numeric values can be read using np.loadtxt().

Concepts Covered

  • Text Files
  • np.loadtxt()

9. Python Program to Check Array Shape After Loading

Problem Statement

Write a Python program to display the shape of a loaded array.

Python Solution

import numpy as np

numbers = np.load("numbers.npy")

print(numbers.shape)

Sample Output

(5,)

Explanation

The .shape attribute shows the dimensions of the loaded array.

Concepts Covered

  • Array Shape
  • .shape

10. Python Program to Save a Matrix to a CSV File

Problem Statement

Write a Python program to save a 3 × 3 matrix as a CSV file.

Python Solution

import numpy as np

matrix = np.array([[1,2,3],
                   [4,5,6],
                   [7,8,9]])

np.savetxt("matrix.csv", matrix, delimiter=",", fmt="%d")

Sample Output

Matrix saved successfully.

Explanation

np.savetxt() is commonly used to export matrices into CSV format.

Concepts Covered

  • Matrix Export
  • CSV Writing

11. Python Program to Save and Load a NumPy Array Using .npy

Problem Statement

Write a Python program to create a NumPy array, save it to a .npy file, and then load it back into memory.

Python Solution

import numpy as np

# Create a NumPy array
array = np.array([10, 20, 30, 40, 50])

# Save the array to a .npy file
np.save("numbers.npy", array)

print("Array saved successfully!")

# Load the array
loaded_array = np.load("numbers.npy")

print("\nLoaded Array:")
print(loaded_array)

Sample Output

Array saved successfully!

Loaded Array:
[10 20 30 40 50]

Explanation

  • np.save() stores the array in binary .npy format.
  • np.load() retrieves the array while preserving its data type and shape.

Concepts Covered

  • np.save()
  • np.load()
  • .npy Files

12. Python Program to Save Multiple Arrays in a .npz File

Problem Statement

Write a Python program to save multiple NumPy arrays into a single .npz file and retrieve them.

Python Solution

import numpy as np

marks = np.array([85, 90, 78, 92])

ages = np.array([20, 21, 22, 23])

np.savez("student_data.npz", marks=marks, ages=ages)

print("Arrays saved successfully!")

data = np.load("student_data.npz")

print("\nMarks:")
print(data["marks"])

print("\nAges:")
print(data["ages"])

Sample Output

Arrays saved successfully!

Marks:
[85 90 78 92]

Ages:
[20 21 22 23]

Explanation

np.savez() allows multiple arrays to be stored in a single compressed archive.

Concepts Covered

  • np.savez()
  • Multiple Arrays
  • NPZ Files

13. Python Program to Save a NumPy Array to a CSV File

Problem Statement

Write a Python program to save a NumPy array into a CSV file using savetxt().

Python Solution

import numpy as np

matrix = np.array([
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90]
])

np.savetxt("matrix.csv", matrix, delimiter=",", fmt="%d")

print("CSV file created successfully!")

Sample Output

CSV file created successfully!

Generated CSV

10,20,30
40,50,60
70,80,90

Explanation

  • delimiter="," separates values with commas.
  • fmt="%d" stores integer values.

Concepts Covered

  • np.savetxt()
  • CSV Files
  • Data Export

14. Python Program to Read Data from a CSV File

Problem Statement

Write a Python program to read numerical data from a CSV file using loadtxt().

Python Solution

import numpy as np

data = np.loadtxt("matrix.csv", delimiter=",")

print("Data Loaded from CSV:")
print(data)

Sample Output

Data Loaded from CSV:
[[10. 20. 30.]
 [40. 50. 60.]
 [70. 80. 90.]]

Explanation

np.loadtxt() reads numerical values from text files such as CSV.

Concepts Covered

  • np.loadtxt()
  • CSV Reading
  • Data Import

15. Python Program to Save Only Specific Columns into a CSV File

Problem Statement

Write a Python program to create a matrix and save only the first two columns into a CSV file.

Python Solution

import numpy as np

matrix = np.array([
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90]
])

selected_columns = matrix[:, :2]

np.savetxt(
    "selected_columns.csv",
    selected_columns,
    delimiter=",",
    fmt="%d"
)

print("Selected columns saved successfully!")

Sample Output

Selected columns saved successfully!

Generated CSV

10,20
40,50
70,80

Explanation

matrix[:, :2] selects all rows and the first two columns before saving.

Concepts Covered

  • Array Slicing
  • CSV Export
  • Column Selection

16. Python Program to Save Floating-Point Numbers with Two Decimal Places

Problem Statement

Write a Python program to save floating-point values into a CSV file with exactly two decimal places.

Python Solution

import numpy as np

values = np.array([
    [10.12345, 20.98765],
    [30.56789, 40.11111]
])

np.savetxt(
    "float_data.csv",
    values,
    delimiter=",",
    fmt="%.2f"
)

print("Floating-point data saved successfully!")

Sample Output

Floating-point data saved successfully!

Generated CSV

10.12,20.99
30.57,40.11

Explanation

fmt="%.2f" limits each floating-point value to two decimal places.

Concepts Covered

  • Floating-Point Formatting
  • savetxt()
  • CSV Precision

17. Python Program to Load a CSV File While Skipping the Header

Problem Statement

Write a Python program to read a CSV file that contains a header row and ignore the header while loading the data.

Example CSV

ID,Marks
101,78
102,85
103,92

Python Solution

import numpy as np

data = np.loadtxt(
    "students.csv",
    delimiter=",",
    skiprows=1
)

print("Student Data:")
print(data)

Sample Output

Student Data:
[[101.  78.]
 [102.  85.]
 [103.  92.]]

Explanation

skiprows=1 tells NumPy to ignore the first line, which contains the column names.

Concepts Covered

  • skiprows
  • Reading CSV
  • Data Cleaning

18. Python Program to Save Student Data with a Header in CSV Format

Problem Statement

Write a Python program to save student information into a CSV file along with column headers.

Python Solution

import numpy as np

students = np.array([
    [101, 85],
    [102, 90],
    [103, 88]
])

np.savetxt(
    "students_marks.csv",
    students,
    delimiter=",",
    fmt="%d",
    header="Student_ID,Marks",
    comments=""
)

print("Student data saved successfully!")

Sample Output

Student data saved successfully!

Generated CSV

Student_ID,Marks
101,85
102,90
103,88

Explanation

  • header= adds column names.
  • comments="" removes the default # symbol before the header.

Concepts Covered

  • CSV Headers
  • np.savetxt()
  • File Formatting

Chapter Summary

In this chapter, you learned how to save and load NumPy arrays using .npy, .npz, and CSV files. You also practiced reading text files, saving compressed arrays, and exporting matrices. These file handling techniques are essential for storing datasets, sharing data, and building real-world data science and machine learning projects.


Key Takeaways

  • np.save() saves arrays in .npy format.
  • np.load() loads .npy files.
  • np.savez() stores multiple arrays.
  • np.savez_compressed() creates compressed files.
  • np.savetxt() exports arrays to CSV.
  • np.loadtxt() imports CSV and text files.
  • .shape displays array dimensions.

Frequently Asked Questions (FAQs)

1. What is the .npy file format?

It is NumPy’s binary file format used to store arrays efficiently.


2. What is the difference between .npy and .npz?

.npy stores one array, while .npz stores multiple arrays in a single file.


3. Which function saves arrays to CSV?

Use np.savetxt().


4. Which function reads CSV files?

Use np.loadtxt().


5. Why should I use np.savez_compressed()?

It reduces file size and saves storage space.


6. Can NumPy read text files?

Yes. Use np.loadtxt() to read numeric text files.


7. Why is NumPy File Handling important?

It helps store, load, and exchange datasets efficiently, making it essential for data science, machine learning, automation, and scientific computing.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top