Найти - Пользователи
Полная версия: [Fixed]::Открытие файла по-новой. Как?
Начало » Python для новичков » [Fixed]::Открытие файла по-новой. Как?
1 2
iandriyanov
Аааа Семен Семенч
EBFE
iandriyanov
Здесь при запуске программы открывается файл с названием out.txt_какая_то_дата, даже если сутки пройдут логи все пишутся и пишутся в него
Может не стоит изобретать велосипед ?
http://docs.python.org/library/logging.handlers.html
Стоит обратить внимание на:
class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
You can use the maxBytes and backupCount values to allow the file to rollover at a predetermined size. When the size is about to be exceeded, the file is closed and a new file is silently opened for output. Rollover occurs whenever the current log file is nearly maxBytes in length
Или
TimedRotatingFileHandler
logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0
You can use the when to specify the type of interval

The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format %Y-%m-%d_%H-%M-%S
Пример:
>>> from logging import handlers
>>> import logging
>>> handler = logging.handlers.TimedRotatingFileHandler("dummy",'S',1)
>>> # S=seconds здесь только для примера
...
>>> handler.suffix
'%Y-%m-%d_%H-%M-%S'
>>> handler.suffix = '%d.%m.%Y_%H_%M_%S'
>>> frm = logging.Formatter("%(asctime)s %(levelname)s: %(message)s","%d.%m.%Y %H:%M:%S")
>>> handler.setFormatter(frm)
>>> handler.setLevel(logging.ERROR)
>>> logger = logging.getLogger('my_sock_logger')
>>> logger.addHandler(handler)
>>> logger.setLevel(logging.DEBUG)
>>> import sys
>>> stdout_handler = logging.StreamHandler(sys.stdout)
>>> stdout_handler.setFormatter(frm)
>>> logger.addHandler(stdout_handler)
>>> logger.error('my sock error1')
17.07.2012 14:25:34 ERROR: my sock error1
>>> logger.error('my sock error2')
17.07.2012 14:25:40 ERROR: my sock error2
>>> exit()
>ls dummy*
dummy  dummy.17.07.2012_14_25_34
>more dummy.17.07.2012_14_25_34
17.07.2012 14:25:34 ERROR: my sock error1
>more dummy
17.07.2012 14:25:40 ERROR: my sock error2
Или
http://stackoverflow.com/questions/1165856/including-current-date-in-python-logging-file
http://docs.python.org/howto/logging-cookbook.html
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB