0

I have a program that performs calculations and shows them in the python console, reviewing a little documentation I have been able to store the results of the console to a txt file.

What I am looking for now is that every time I rerun the txt file is cleaned, so that the previous results of the console are not accumulated in the txt.

from loggerPrint import Logger

print_console = Logger('out_of_console.txt') 

print('This is an example:')
print('Element',5*' ', 'Value')

values = [1,2,3,4,5,6,7,8,9,10]

for i in values:
    print(i,11*' ', values[5])

print_console.close()

The class

import sys, os

class Logger(object):
    """
    Lumberjack class - duplicates sys.stdout to a log file and it's okay
    source: https://stackoverflow.com/a/24583265/5820024
    """
    def __init__(self, filename="Prints_k", mode="ab", buff=0):
        self.stdout = sys.stdout
        self.file = open(filename, mode, buff)
        sys.stdout = self
    
    def __del__(self):
        self.close()
    
    def __enter__(self):
        pass
    
    def __exit__(self, *args):
        pass
    
    def write(self, message):
        self.stdout.write(message)
        self.file.write(message.encode("utf-8"))
    
    def flush(self):
        self.stdout.flush()
        self.file.flush()
        os.fsync(self.file.fileno())
    
    def close(self):
        if self.stdout != None:
            sys.stdout = self.stdout
            self.stdout = None
    
        if self.file != None:
            self.file.close()
            self.file = None

While searching, I found the class 'Logger', in my case it works if in the write method the variable is defined like this: self.file.write (message.encode ("utf-8")), I leave a little more documentation in the following link: How to print the console to a text file AFTER the program finishes (Python)?

If someone has experience in handling classes and understands a little better, I would appreciate it, you could include a new method called clear, or do it in another way.

Best regards.

DaniV
  • 489
  • 2
  • 9

2 Answers2

1

The __init__ method in the Logger class opens the file in 'ab' mode.
a = append
b = binary

If you want always write to a new file and not keep the old contents open the file in 'wb' mode.

def __init__(self, filename="Prints_k", mode="wb", buff=0):

https://docs.python.org/3.3/tutorial/inputoutput.html#reading-and-writing-files

PiyushC
  • 308
  • 1
  • 9
  • Thank you very much for your contribution and for the documentation, a cordial greeting, @Piyush C. – DaniV Aug 07 '20 at 21:02
1

good job finding that class! You can see that when you instantiate it with

print_console = Logger('out_of_console.txt')

the argument mode is kept at its default value "ab".

Referring to : https://stackabuse.com/file-handling-in-python/ this corresponds to opening the file in "append byte" mode, where new input is added to the file as you write. You need to write

print_console = Logger('out_of_console.txt',mode="wb")

in order for the file to be cleared before writing to it.

ju95ju
  • 847
  • 1
  • 5
  • 20