简体   繁体   English

用python将多个返回值写入文件

[英]writing multiple returns to a file in python

I need to write the returns of each function in to a text file. 我需要将每个函数的返回结果写入文本文件。 I have used the code below. 我用下面的代码。 However, when I have multiple functions, this process of using file1.write() consumes a lot of time and lines. 但是,当我有多个功能时,使用file1.write()的过程将花费大量时间和行。 Is there any smarter method to write the outputs? 有没有更聪明的方法来写输出?

def function1():
    #some operation
    return "Status 1" + "\n\n"

def function2():
    #some operation
    return "Status 2" + "\n\n"

def function3():
    #some operation
    return "Status 1" + "\n\n"

if __name__ == '__main__':

    file1 = open("test.txt","w")

    output1 = function1()
    file1.write(output1)

    output2 = function2()
    file1.write(output2)

    output3 = function3()
    file1.write(output3)

    file1.close()

I have modified the code since many are confused with my question. 我修改了代码,因为许多人对我的问题感到困惑。

This code can be made shorter (and possibly clearer) by replacing everything below if by: 此代码可以通过更换所有变短(以及可能的更清楚)所示if由:

with open("text.txt","w") as file1:
    for func in (addition, subtraction, multiplication):
        file1.write(func(5,6))

but this won't improve execution time. 但这不会缩短执行时间。

It looks like you're trying not to repeat yourself so much. 看来您正努力避免重复太多。 You can take advantage of the fact that functions are "first class objects" in order to iterate over them. 您可以利用以下事实:函数是“一流的对象”,以便对其进行迭代。 Also, you can take advantage of the features of the functools module to reuse the basic structure of nearly identical functions. 另外,您可以利用functools模块的功能来重用几乎相同功能的基本结构。 The following code will produce identical output to your example with far less repetition of code: 以下代码将以更少的重复代码产生与您的示例相同的输出:

import functools

def base_func(func_id):
    return 'status of {}\n\n'.format(func_id)

functions = [functools.partial(base_func, i+1) for i in range(3)]

if __name__ == '__main__':
    with open('test.txt','w') as file1:
        for func in functions:
            file1.write(func())

However, it will almost certainly not run execute any faster, but given your example I'd hardly thing computing performance should be of great concern. 但是,几乎可以肯定它不会以更快的速度运行,但是考虑到您的示例,我几乎不会担心计算性能。

The fastest text writer I've come across is Pandas, which I usually use with NumPy. 我遇到的最快的文本编写器是Pandas,我通常将其与NumPy一起使用。 So it would look something like this: 所以看起来像这样:

import pandas as pd
import numpy as np
a=np.zeros(len(results)) #if you know the result size
#now store all your results in a
a[0]=add(5,6)
a[1]=sub(5,6)
a[2]=multiply(5,6)
#continue
b=pd.DataFrame(a)
b.to_csv('test.csv', header=False, index=False, sep=',')

Hope you get the idea - sep can be any delimiter. 希望您能想到-sep可以是任何分隔符。 If you need a multidimensional array you can do that too. 如果需要多维数组,也可以这样做。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM