×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python - How to set the fmt option in numpy.savetxt()?

Learn, how to set the fmt option in numpy.savetxt() in Python? By Pranit Sharma Last updated : December 28, 2023

Setting the fmt option in numpy.savetxt()

The numpy.savetxt() is used to save an array to a text file. It accepts many parameters which include x (data to be saved), delimiter (string or character which separated the columns) and fmt.

The fmt is a string type or sequence of string type parameters that represent a sequence of formats or a multi-format string.

For example, in Iteration %d – %10.5f, delimiter is ignored. If the data is complex, there are some legal formats:

  • a single specifier, fmt='%.4e', resulting in numbers formatted like ' (%s+%sj)' % (fmt, fmt)
  • a full string specifying every real and imaginary part, e.g. ' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'for 3 columns
  • a list of specifiers, one per column - in this case, the real and imaginary part smust have separate specifiers, e.g. ['%.3e + %.3ej', '(%.15e%+.15ej)']for 2 columns.

In broader context, we can add or modify the data in certain format using the fmt parameter. If we need toset a float precision, we can use fmt='%1.3f'.

Python code to set the fmt option in numpy.savetxt()

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.arange(0.0,5.0,1.0)

# Display original array
print("Original array:\n",arr,"\n")

# Saving data with a specific format
np.savetxt('hello.txt', arr, fmt='%1.3f')

print("file saved")

Output

Example: Setting the fmt option in numpy.savetxt()

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.