简体   繁体   English

python:防止创建空文件

[英]python: prevent creating empty files

For a bulk task I create a couple of instances of the ProgressLog object which will each create an empty log-file no matter if there actually will be any errors. 对于批量任务,我创建了ProgressLog对象的几个实例,每个实例都会创建一个空的日志文件,无论是否实际存在任何错误。 what is the best way to prevent this? 预防这种情况的最佳方法是什么?

class ProgressLog(object):
    """Write a message to log + progress indicator.

    """
    total = 0

    def __init__(self, name):
        source_path, file_name = os.path.split(name)
        self.name = file_name
        self.source_path = source_path
        self.log_dir_name = r'log'
        self.make_log_dir(self.source_path, self.log_dir_name)
        self.reset()
        log_file = self._logfilename()
        try:
            self.f = open(log_file, 'w')
            print('\n***logging errors to {0}***\n'.format(log_file))
        except IOError, err:
            msg = 'Cannot open logfile {0}. Traceback is: {1}'.format(
                log_file, err)
            raise msg

    def _logfilename(self):
        ## hms_ddmmyyyy format
        log_name = r'{1}_{0}{2}_errors.csv'.format(
                                  time.strftime("%I%M%S"),
                                  time.strftime("%d%m%Y"),
                                  self.name)
        return os.path.join(self.source_path, self.log_dir_name, log_name)

There is no "magical" way to do it, you simply need to refactor the code to open the log file only on first actual call to log. 没有“神奇”的方法,只需重构代码即可仅在第一次实际调用log时打开日志文件。

To achieve this, extract the part of __init__ that opens the log file into a separate _open_log method. 为此,请将__init__的一部分打开日志文件,并将其_open_log压缩到单独的_open_log方法中。 In __init__ initialize self.f to None . __init__ self.f初始化为None Then, your actual logging method can begin with: 然后,您的实际记录方法可以开始于:

if self.f is None:
    self._open_log()

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

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