# -*- coding: utf-8 -*- """ Created on Mon Sep 28 14:12:11 2020 @author: jbobowsk """ # This Python script is designed to show you how to export data to a file. # First a very simple example. We generate an x array with elements 1 to # 10 in steps of 2. We also calculate y2 and y3 values as x^2 and x^3, # respectively. import numpy as np x = np.arange(1, 10, 2) y2 = x**2 y3 = x**3 print(x, y2, y3) # Ultimately, I intend to export a matrix of data to my file. The matrix # is constructed as follows: M1= np.matrix([x, y2, y3]) print(M1) # The matrix above has x as the first row, y2 as the second row, and y3 as # the third row. I'd rather have x as the first column, y2 as the second # column, and y3 as the third column. This is achieved by transposing the # matrix above. M2 = np.transpose(M1) print(M2) # We will use 'np.savetxt()' to write the data to a file. This line will write the # data to a file in the same directory as the Python script (.py file). # The file does not need to exist in order to execute this command. # If the file doesn't exist, it will be created. If the file does exist # already, it will be overwritten. np.savetxt('matrix data.txt', M2) # You can, of course, specify a different folder. The line below will # write the file to a folder called 'data folder' which is contained within # the same folder as the python script. This time 'data folder' must # actually exist for the command to be executed properly. np.savetxt('data folder/matrix data.txt', M2) # You can also specify a path that is independent of the loaction of the # Python script. np.savetxt('G:/UBCO/2020-2021/Python/20200928/data folder/matrix data.txt', M2) # Suppose that you now wanted to appenda row of data to the 'matrix data' file # that we just created. You can do this by openning the file in append mode # i.e. using the 'a' option in 'open()' and the using 'np.savetxt()' again. # Note that the 'with' statement closes the file after indented lines of code # have executed. newRow = [[11, 11**2, 11**3]] with open('matrix data.txt', 'a') as f: np.savetxt(f, newRow) # Let's import the data file to verify that it has been written properly. Data = np.loadtxt('matrix data.txt') print(Data)