How To Save An Array in Python

Updated at 15-Nov-2022, By samar

How To Save An Array in Python

Good day, friends. In this post, we’ll learn, How To Save An Array in Python.

We have to use NumPy which is a Python library used for working with arrays. function is used to store the input array in a disk file with npy extension (file.npy) in python.

  • Save array in python using NumPy Library

    Install numpy using terminal

    pip install numpy

    Example code to save array in a file using NumPy

    import numpy as np
    a = np.arange(10)
    print(a)'pythonfile', a)
    print("the array is saved in the file pythonfile.npy")


    [0 1 2 3 4 5 6 7 8 9 10]

    You can save numpy array to a file using method and then later, load into an array using numpy.load().

  • Save an array into a CSV file in python using numpy

    You have to use np.tofile() function to write Python array into CSV file. Install numpy library using below command before using it.

    pip install numpy

    Create a file and add below code in it.

    import numpy as np
    arr = np.asarray([ [7,8,9], [5,8,9] ])
    arr.tofile('sample.csv', sep = ',')

    Create sample.csv file and Run python in terminal to add array to csv file in python.

  • Save an array in a csv file using numpy with panda dataframe

    You have to create a and sample-pddf.csv file in root directory. Before using numpy and pandas library you have to install it using pip install command. Now you have to run python in your terminal to save array to csv file using numpy and padas dataframe.

    Run below command in your terminal before using numpy and pandas library.

    pip install numpy
    pip install pandas


    import numpy as np
    import pandas as pd
    arr = np.asarray([ [7,8,9], [5,8,9] ])
    pd.DataFrame(arr).to_csv('sample-pddf.csv', index_label = "Index", header  = ['a','b','c'])
  • Save a Python list to a file

    Create list names = ['John', 'Doe', 'Bob'].

    Open file in write mode eg: with open(r'./info.txt', 'w') as fp:.

    Iterate list using a for loop for item in names:.

    Write List item to info.txt file fp.write("%s\n" % item).

  • How do I save an array as a text in Python?

    Use numpy.savetxt() to save an array to a text file.

    First import numpy library in python using command in terminal - pip install numpy.

    Open file in write mode >> a_file = open("test.txt", "w")

    Loop array >> for row in an_array:

    Save data in file >> np.savetxt(a_file, row)

    Close file >> a_file.close()

Back to code snippet queries related python