Bird
Raised Fist0
NumPydata~10 mins

np.savetxt() and np.loadtxt() for text in NumPy - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - np.savetxt() and np.loadtxt() for text
Create or have a numpy array
↓
Use np.savetxt() to write array to text file
↓
File saved on disk as plain text
↓
Use np.loadtxt() to read text file back into numpy array
↓
Array loaded in memory, same shape and values
This flow shows saving a numpy array to a text file and then loading it back as an array.
Execution Sample
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]])
np.savetxt('data.txt', arr, fmt='%d')
loaded = np.loadtxt('data.txt', dtype=int)
Save a 2x2 integer array to 'data.txt' and load it back into 'loaded'.
Execution Table
StepActionInput/ConditionResult/Output
1Create arrayarr = [[1, 2], [3, 4]]arr is a 2x2 numpy array with integers
2Call np.savetxtfilename='data.txt', arr, fmt='%d'File 'data.txt' created with text: 1 2 3 4
3Call np.loadtxtfilename='data.txt', dtype=intloaded is a 2x2 numpy array with values [[1, 2], [3, 4]]
4Check equalitynp.array_equal(arr, loaded)True
💡 Finished saving and loading array, data matches original
Variable Tracker
VariableStartAfter Step 1After Step 3Final
arrundefined[[1 2] [3 4]][[1 2] [3 4]][[1 2] [3 4]]
loadedundefinedundefined[[1 2] [3 4]][[1 2] [3 4]]
Key Moments - 3 Insights
Why do we need to specify fmt='%d' in np.savetxt?
Without fmt='%d', np.savetxt saves floats by default, which can add decimals. Specifying '%d' saves integers exactly as in the execution_table step 2.
What happens if the file 'data.txt' does not exist when calling np.loadtxt?
np.loadtxt will raise a FileNotFoundError because it cannot find the file to read, as shown in execution_table step 3 where the file must exist.
Does np.loadtxt always return the same shape array as saved?
Yes, if the file format matches and data is consistent, np.loadtxt returns the same shape, as seen in execution_table step 3 and variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the content of 'data.txt' after step 2?
A"1 2\n3 4"
B"[1 2]\n[3 4]"
C"1,2\n3,4"
D"1.0 2.0\n3.0 4.0"
💡 Hint
Check the Result/Output column in execution_table row 2 for the exact file content.
At which step does the variable 'loaded' get its value?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the Action column in execution_table where np.loadtxt is called.
If we remove fmt='%d' from np.savetxt, how would the file content change?
AIt would save the array as binary
BIt would save integers as floats with decimals
CIt would not save anything
DIt would save the array with commas
💡 Hint
Refer to key_moments question about fmt='%d' and execution_table step 2.
Concept Snapshot
np.savetxt(filename, array, fmt) saves a numpy array to a text file.
np.loadtxt(filename, dtype) loads the text file back as a numpy array.
Use fmt='%d' to save integers without decimals.
The saved file is plain text with rows and columns.
Loaded array matches the original shape and values.
Full Transcript
This lesson shows how to save a numpy array to a text file using np.savetxt and then load it back using np.loadtxt. First, we create a 2x2 integer array. Then, np.savetxt writes this array to a file named 'data.txt' with integer formatting to avoid decimals. Next, np.loadtxt reads the file and recreates the array in memory. The loaded array matches the original exactly in shape and values. Key points include specifying the format to control how data is saved and ensuring the file exists before loading. This process is useful for saving data in a human-readable text format and loading it later for analysis.

Practice

(1/5)
1. What is the main purpose of np.savetxt() in NumPy?
easy
A. To convert a NumPy array into a Python list
B. To load a NumPy array from a binary file
C. To save a NumPy array to a text file in a readable format
D. To display a NumPy array on the screen

Solution

  1. Step 1: Understand the function purpose

    np.savetxt() is designed to save arrays to text files, making the data readable and shareable.
  2. Step 2: Compare with other options

    Options B, C, and D describe different functions or actions unrelated to saving arrays as text files.
  3. Final Answer:

    To save a NumPy array to a text file in a readable format -> Option C
  4. Quick Check:

    np.savetxt() saves arrays to text files [OK]
Hint: Remember: savetxt saves arrays as readable text files [OK]
Common Mistakes:
  • Confusing savetxt with loadtxt
  • Thinking it saves to binary files
  • Assuming it converts arrays to lists
2. Which of the following is the correct syntax to save a 2D NumPy array arr to a file named data.txt using np.savetxt()?
easy
A. np.savetxt('data.txt', arr)
B. np.savetxt(arr, 'data.txt')
C. np.save('data.txt', arr)
D. np.loadtxt('data.txt', arr)

Solution

  1. Step 1: Recall the correct parameter order for np.savetxt()

    The first argument is the filename (string), the second is the array to save.
  2. Step 2: Check each option

    np.savetxt('data.txt', arr) matches the correct order. np.savetxt(arr, 'data.txt') reverses the order. np.save('data.txt', arr) uses np.save which saves binary files. np.loadtxt('data.txt', arr) uses np.loadtxt which reads files, not saves.
  3. Final Answer:

    np.savetxt('data.txt', arr) -> Option A
  4. Quick Check:

    Filename first, array second in np.savetxt() [OK]
Hint: Filename goes first, array second in np.savetxt() [OK]
Common Mistakes:
  • Swapping filename and array arguments
  • Using np.save instead of np.savetxt
  • Confusing np.loadtxt with np.savetxt
3. What will be the output of the following code?
import numpy as np
arr = np.array([[1, 2], [3, 4]])
np.savetxt('temp.txt', arr, fmt='%d', delimiter=',')
loaded = np.loadtxt('temp.txt', delimiter=',', dtype=int)
print(loaded)
medium
A. SyntaxError
B. [[1, 2], [3, 4]]
C. [1 2 3 4]
D. [[1 2] [3 4]]

Solution

  1. Step 1: Understand saving with delimiter and format

    The array is saved as text with comma delimiter and integer format, so the file lines look like '1,2' and '3,4'.
  2. Step 2: Loading with matching delimiter and dtype

    Using np.loadtxt with delimiter=',' and dtype=int reads the file back into a 2D integer array.
  3. Step 3: Print output format

    Printing a NumPy array shows it with spaces between elements and new lines for rows, so output is [[1 2] [3 4]].
  4. Final Answer:

    [[1 2] [3 4]] -> Option D
  5. Quick Check:

    Loadtxt reads saved text back as array [OK]
Hint: Match delimiter and dtype when loading saved text [OK]
Common Mistakes:
  • Expecting list output instead of array
  • Missing delimiter in loadtxt causing errors
  • Using wrong dtype causing float instead of int
4. Identify the error in this code snippet:
import numpy as np
arr = np.array([1.5, 2.5, 3.5])
np.savetxt('file.txt', arr, fmt='%d')
loaded = np.loadtxt('file.txt', dtype=float)
print(loaded)
medium
A. Using '%d' format truncates floats to integers when saving
B. np.loadtxt cannot read float data
C. Missing delimiter argument causes error
D. Array must be 2D to use np.savetxt

Solution

  1. Step 1: Check format string in np.savetxt()

    The format '%d' saves numbers as integers, so 1.5, 2.5, 3.5 become 1, 2, 3 in the file.
  2. Step 2: Loading with dtype=float

    Loading back as float converts these integers to floats 1.0, 2.0, 3.0, losing original decimal parts.
  3. Step 3: Identify the error

    The error is the format string truncates data, causing loss of precision.
  4. Final Answer:

    Using '%d' format truncates floats to integers when saving -> Option A
  5. Quick Check:

    Format string controls saved data type [OK]
Hint: Use '%f' to save floats, not '%d' [OK]
Common Mistakes:
  • Assuming loadtxt can't read floats
  • Thinking delimiter is required for 1D arrays
  • Believing np.savetxt requires 2D arrays only
5. You have a 2D NumPy array with mixed integer and float values. You want to save it to a text file with comma separation and load it back preserving the exact values. Which code snippet correctly achieves this?
hard
A. np.savetxt('data.csv', arr, delimiter=',', fmt='%d') loaded = np.loadtxt('data.csv', delimiter=',', dtype=float)
B. np.savetxt('data.csv', arr, delimiter=',', fmt='%.2f') loaded = np.loadtxt('data.csv', delimiter=',')
C. np.savetxt('data.csv', arr, delimiter=';') loaded = np.loadtxt('data.csv', delimiter=',')
D. np.savetxt('data.csv', arr) loaded = np.loadtxt('data.csv', delimiter=',')

Solution

  1. Step 1: Choose correct format for mixed data

    Using fmt='%.2f' saves all numbers as floats with 2 decimals, preserving float and integer values.
  2. Step 2: Match delimiter in save and load

    Both saving and loading use delimiter=',' ensuring data is correctly split on commas.
  3. Step 3: Check other options for errors

    np.savetxt('data.csv', arr, delimiter=',', fmt='%d') loaded = np.loadtxt('data.csv', delimiter=',', dtype=float) uses '%d' which truncates floats. np.savetxt('data.csv', arr, delimiter=';') loaded = np.loadtxt('data.csv', delimiter=',') mismatches delimiters. np.savetxt('data.csv', arr) loaded = np.loadtxt('data.csv', delimiter=',') saves without delimiter but loads with comma, causing errors.
  4. Final Answer:

    np.savetxt('data.csv', arr, delimiter=',', fmt='%.2f') loaded = np.loadtxt('data.csv', delimiter=',') -> Option B
  5. Quick Check:

    Match format and delimiter to preserve data [OK]
Hint: Use float format and matching delimiter both ways [OK]
Common Mistakes:
  • Using integer format for float data
  • Mismatching delimiters between save and load
  • Not specifying format causing precision loss