简体   繁体   English

如何将数据写入来自 Python 中的 function 的文件?

[英]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:我有 function 接受 4 arguments 如下所示:

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.我想将 x 和 v 写入文件,但我不太确定如何。 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()

Your function returns a tuple and you can easily write a tuple to an external file if you convert it to string.您的 function 返回一个元组,如果将元组转换为字符串,您可以轻松地将其写入外部文件。 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.但不清楚您的目标是什么,以及这是否是实现目标的正确方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何去完成一个子功能,然后又回到我原来的“菜单功能”? (蟒蛇) - How do I go to, and finish one sub function, and then revert back to the “menu function” that I came from? (python) 如何使用 function “图像” Python 图像库中的像素数据写入二进制文件? - How do I write to a binary file using pixel data from the function “image” the Python Image Library? 如何打印项目以及它来自Python的列表? - How do I print an item and the list it came from in Python? 如何编写读取 a.data 文件并在 python 中返回 np 数组的 function? - How do I write a function that reads a .data file and returns an np array in python? 如何将数据写入从Python中的SQL数据库获取的文件中? (sqlite3的) - How do I write data to a file that I have taken from an SQL database in Python? (sqlite3) 如何为 Python 的可变数量输入数据编写 function? - How do I write a function for Varied amount input data for Python? 如何在 Python 中将二进制数据写入文本文件? - How do I write binary data to a text file in Python? 如何使用 Python 自动将数据写入 Excel 文件? - How do I write data into an Excel file automatically using Python? 如何将 python 中的数据逐行写入 csv 文件? - How do I write data from python line by line to csv file? 如何将数据从python列表中的列和行写入csv文件? - How do I write data to csv file in columns and rows from a list in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM