在循环中,可选择将输出写入文件

J-J*_*J-J 1 python output

我编写了一个函数,它迭代计算一些数量X,Y,返回最终结果。此外,此代码将每次迭代保存X,Y到文件中。这是基本结构:

def myFunc():
    X,Y = 0,0
    file1 = open(output1,"w")
    file2 = open(output2,"w")
    for i in range(1000):
        X,Y = someCalculation(X,Y) #calculations happen here
        file1.write(X)
        file2.write(Y)
    file1.close()
    file2.close()
    return X,Y
Run Code Online (Sandbox Code Playgroud)

但是,如果调用函数时省略文件名output1或,我需要此函数执行相同的计算,而不向相关文件添加任何内容output2

这是我的凌乱的解决方案:

def myFunc(output1=None,output2=None):
    X,Y = 0,0
    if (output1 != None): file1 = open(output1,"w")
    if (output2 != None): file2 = open(output2,"w")
    for i in range(1000):
        X,Y = someCalculation(X,Y) #calculations happen here
        if (output1 != None): file1.write(X)
        if (output2 != None): file2.write(Y)
    if (output1 != None): file1.close()
    if (output2 != None): file2.close()
    return X,Y
Run Code Online (Sandbox Code Playgroud)

有没有更好、更简洁的方式来写这个?

Kar*_*tel 5

制作一个忽略写入的虚拟文件对象,并支持上下文管理器接口:

class NoFile:
    def __enter__(self): return self
    # Propagate any exceptions that were raised, explicitly.
    def __exit__(self, exc_type, exc_value, exc_tb): return False
    # Ignore the .write method when it is called.
    def write(self, data): pass
    # We can extend this with other dummy behaviours, e.g.
    # returning an empty string if there is an attempt to read.
Run Code Online (Sandbox Code Playgroud)

创建一个辅助函数,当文件名如下时创建其中一个文件而不是普通文件is None

def my_open(filename, *args, **kwargs):
    return NoFile() if filename is None else open(filename, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

使用with块来管理文件生命周期,无论如何你都应该这样做 - 但现在使用my_open而不是open

def myFunc(output1=None,output2=None):
    X, Y = 0, 0
    with my_open(output1, 'w') as f1, my_open(output2, 'w') as f2:
        for i in range(1000):
            X, Y = someCalculation(X, Y) #calculations happen here
            f1.write(X)
            f2.write(Y)
    return X, Y
Run Code Online (Sandbox Code Playgroud)