Working with Text Files in Numpy: savetxt and loadtxt

Numpy provides simple methods for reading from and writing to text files. These methods, savetxt and loadtxt, allow you to work with structured or unstructured data stored in plain text format.

1. Writing Data to a Text File: savetxt

The savetxt function in Numpy allows you to save arrays to text files. This function can handle both numerical and string data, and you can also specify the format for each element.

    import numpy as np
    
    # Creating a sample 2D array
    data = np.array([[1.5, 2.3, 3.8],
                     [4.1, 5.2, 6.3],
                     [7.4, 8.5, 9.6]])
    
    # Saving the array to a text file
    np.savetxt('data.txt', data)
    print("Data saved successfully.")
        

In this example, we create a 2D Numpy array and save it to a text file named data.txt. The saved file will contain the numbers arranged in rows and columns.

Result

The content of data.txt will look like this:

    1.5 2.3 3.8
    4.1 5.2 6.3
    7.4 8.5 9.6
        

2. Reading Data from a Text File: loadtxt

The loadtxt function is used to load data from a text file into a Numpy array. This function can also be customized to handle different delimiters, data types, and other parameters.

    # Loading the data from the text file
    loaded_data = np.loadtxt('data.txt')
    
    # Displaying the loaded data
    print("Loaded data:")
    print(loaded_data)
        

In this example, we load the data from data.txt into a Numpy array and print it.

Result

The output will be:

    Loaded data:
    [[1.5 2.3 3.8]
     [4.1 5.2 6.3]
     [7.4 8.5 9.6]]
        

3. Customizing Output Format with savetxt

You can customize how the data is saved in the text file by specifying a delimiter or fmt parameter. For example, you can save the data in CSV (Comma Separated Values) format or specify the number of decimal places.

    # Saving the array with a custom delimiter and format
    np.savetxt('formatted_data.csv', data, delimiter=',', fmt='%.2f')
    print("Data saved in CSV format.")
        

Result

The content of formatted_data.csv will now be saved with a comma as the delimiter and two decimal places:

    1.50,2.30,3.80
    4.10,5.20,6.30
    7.40,8.50,9.60
        

4. Handling Text Data

You can also use savetxt and loadtxt to save and load string data. Here’s how:

    # Creating a string array
    string_data = np.array([['Hello', 'World'],
                            ['Python', 'Numpy'],
                            ['Text', 'Files']])
    
    # Saving the string array to a text file
    np.savetxt('string_data.txt', string_data, fmt='%s')
    print("String data saved successfully.")
        

After running this, the content of string_data.txt will look like:

    Hello World
    Python Numpy
    Text Files
        

Loading the String Data

    # Loading the string data
    loaded_string_data = np.loadtxt('string_data.txt', dtype=str)
    
    # Displaying the loaded data
    print("Loaded string data:")
    print(loaded_string_data)
        

The output will display:

    Loaded string data:
    [['Hello' 'World']
     ['Python' 'Numpy']
     ['Text' 'Files']]
        

Conclusion

The savetxt and loadtxt functions in Numpy are powerful tools for working with text files. They allow you to store and retrieve data efficiently, and can handle both numerical and string data. By adjusting the format and delimiter parameters, you can customize how the data is saved and loaded to meet your needs.





Advertisement