python中的全局文件初始化

2024-04-26 22:26:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在搜索如何创建一个全局文件,它将打开,直到我的申请完成。需要在单个文件中写入视图中所有模块的输出。这样,一旦应用程序从前端运行完成,用户就可以下载此文件作为报告。这是我创建的类

import time


class FileOperations:
    def __init__(self):

        self.current_time = time.strftime('%Y-%m-%d_%H-%M-%S')
        self.outfile = open("reports/username_" + self.current_time + ".txt", 'w')
        self.outfile.write("Final Report \n")
        self.outfile.write("*****************")

我希望此文件在应用程序开始运行时生成,并且应可用于所有模块


Tags: 模块文件用户importself视图应用程序time
1条回答
网友
1楼 · 发布于 2024-04-26 22:26:30

上下文管理器是一种安全地处理诸如写入文件之类的操作的方法。它还允许您更好地跟踪文件何时打开或关闭。 我建议您在应用程序启动时花点时间,并按照我的预期重用该文件。这可能比打开文件更“安全”。你知道吗

def get_time():
    global start_time
    start_time = time.strftime('%Y-%m-%d_%H-%M-%S')

def write_to_file():
    with open('reports/username_{}.txt'.format(start_time), 'a') as f:
      f.write("Final Report \n")
      f.write("*****************")

if 'start_time' not in globals():
    get_time()

每次导入模块时都将运行条件。通过检查它是否已经在模块范围中定义,我们确保只定义一次。你知道吗

相关问题 更多 >