Search code examples
pythonfunctionwritetofile

how do I write data to file that came from a function in Python?


I have function that takes in 4 arguments as shown below:

def Euler(nsteps, k , m , b):
    nsteps = int(time_interval/step_size)
    # Create empty arrays ready for the values of x and v
    x = np.zeros(nsteps)
    v = np.zeros(nsteps)
    # Choose some initial conditions
    x[0] = 0.0
    v[0] = -1.0
    for i in range(nsteps-1):
        # Calculate the acceleration at step i
        a = -(k/m)*x[i] - (b/m)*v[i]
        # For each configuration at step i, calculate x and v for the later step i+1
        x[i+1] = x[i] + v[i]*step_size
        v[i+1] = v[i] + a*step_size
    return x, v

I want to write x and v to a file but I'm not too sure how. This is what I have and it doesn't work. does anyone know how to fix this please?

Euler_method = open('Euler_method.txt' , 'w')
Euler_method.write(Euler(nsteps, k, m, b))
Euler_method.close()

Solution

  • Your function returns a tuple and you can easily write a tuple to an external file if you convert it to string. Thus, just change your code:

    Euler_method = open('Euler_method.txt' , 'w')
    Euler_method.write(str(Euler(nsteps, k, m, b)))
    Euler_method.close()
    

    But it is not clear what your objective is and if this is the right way to accomplish your objective.