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

发布于 2025-02-10 16:55:32 字数 1062 浏览 1 评论 0原文

我编写了一个迭代性计算一些数量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

但是,如果文件名 或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

是否有一种更好,更干净的写作方式?

I wrote a function which iteratively computes some quantities X,Y, returning the final result. Additionally, this code saves each iteration of X,Y to a file. Here is the basic structure:

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

However, if the filename output1 or output2 is omitted when the function is called, I need this function to perform the same calculation without appending anything to the relevant file.

Here is my messy solution:

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

Is there a better, cleaner way to write this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

亢潮 2025-02-17 16:55:32

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

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.

创建一个辅助函数,当文件名 none 时,创建其中一个而不是普通文件:

def my_open(filename, *args, **kwargs):
    return NoFile() if filename is None else open(filename, *args, **kwargs)

使用代码>块来管理文件寿命,就像您应该做的那样 - 但是现在使用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

Make a dummy file object that ignores writes, and supports the context manager interface:

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.

Make a helper function that creates one of these instead of a normal file when the filename is None:

def my_open(filename, *args, **kwargs):
    return NoFile() if filename is None else open(filename, *args, **kwargs)

Use with blocks to manage the file lifetimes, as you should do anyway - but now use my_open instead of 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
两相知 2025-02-17 16:55:32

您可以创建一个虚拟类,该类没有do <代码>写方法。 ExitStack用于确保自动关闭任何打开的文件。

from contextlib import ExitStack


class NoWrite:
    def write(self, value):
        pass


def myFunc(output1=None, output2=None):
    X,Y = 0,0
    with ExitStack() as es:
        file1 = es.enter_context(open(output1, "w")) if output1 is not None else NoWrite()
        file2 = es.enter_context(open(output2, "w")) if output2 is not None else NoWrite()

        for i in range(1000):
            X,Y = someCalculation(X, Y) #calculations happen here
            file1.write(X)
            file2.write(Y)
    return X,Y

当您似乎正在记录x和/或y值时,您可能需要考虑使用logging模块,为适当的记录器创建fileHandler,而不是将输出文件名称为myFunc本身。

import logging

# configuration of the logger objects is the responsibility
# of the *user* of the function, not the function itself.
def myFunc():
    x_logger = logging.getLogger("myFunc.x_logger")
    y_logger = logging.getLogger("myFunc.y_logger")

    X,Y = 0,0
    for i in range(1000):
        X,Y = someCalculation(X, Y)
        x_logger.info("%s", X)
        y_logger.info("%s", Y)
    return X,Y

You can create a dummy class that has a do-nothing write method. ExitStack is used to ensure any opened files are closed automatically.

from contextlib import ExitStack


class NoWrite:
    def write(self, value):
        pass


def myFunc(output1=None, output2=None):
    X,Y = 0,0
    with ExitStack() as es:
        file1 = es.enter_context(open(output1, "w")) if output1 is not None else NoWrite()
        file2 = es.enter_context(open(output2, "w")) if output2 is not None else NoWrite()

        for i in range(1000):
            X,Y = someCalculation(X, Y) #calculations happen here
            file1.write(X)
            file2.write(Y)
    return X,Y

As you appear to be logging the X and/or Y values at each step, you may want to look into using the logging module instead, creating a FileHandler for the appropriate logger instead of passing output file names to myFunc itself.

import logging

# configuration of the logger objects is the responsibility
# of the *user* of the function, not the function itself.
def myFunc():
    x_logger = logging.getLogger("myFunc.x_logger")
    y_logger = logging.getLogger("myFunc.y_logger")

    X,Y = 0,0
    for i in range(1000):
        X,Y = someCalculation(X, Y)
        x_logger.info("%s", X)
        y_logger.info("%s", Y)
    return X,Y
家住魔仙堡 2025-02-17 16:55:32

简单:写入操作系统定义的“空设备”文件,以免写信给。

标准库OS模块定义字符串常数devNull,它标识了此文件的路径:'/dev/null' Mac and Linux上'nul'在Windows上(我想后者实际上不是路径)。

import os
def myFunc(output1=os.devnull,output2=os.devnull):
    # as before, with no special conditional logic

Simpler: write to a "null device" file defined by your operating system to have no effect when written to.

The standard library os module defines a string constant devnull which identifies the path to this file: '/dev/null' on Mac and Linux, 'NUL' on Windows (I suppose the latter is not actually a path).

import os
def myFunc(output1=os.devnull,output2=os.devnull):
    # as before, with no special conditional logic
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文