Forum Archive

How to save a log file to Pythonista file system

OTPSkipper

How can I save a log file to my pythonista file system?

dgelessus

You can use the normal Python open function, like you would with a normal Python installation on a regular computer. (For details on how to use open, see the Python standard library docs, section "Built-in Functions". Most Python tutorials and beginner's books will also explain how open works.)

By default, all file names are relative to the folder that your script is in, so if you use open("mylog.txt", "w"), a file mylog.txt will be created in the same folder that the script is in. If you want to always use a fixed path, you can use something like open(os.path.expanduser("~/Documents/logs/mylog.txt"), "w"). ~/Documents is the "Library" that you see in Pythonista's file list, so this will create a file mylog.txt in the folder logs.

OTPSkipper

Hmmm. Tried that and it didn't seem to work. No file showed up.

dgelessus

Can you post your code? Otherwise it's difficult to tell what might be going wrong.

OTPSkipper

Simple enough. Logfile_out is set to "log.txt"

  if self.logfile_out is not None:
        self._of = open(self.logfile_out, mode='w', encoding='utf-8')

It has to be something stupid.

ccc

Is self.logfile_out a file name or a file pointer? The last line seems to indicate that it is a file name (i.e. a string). An empty string '' != None. This is the sort of thing that typechecking will help with in Python 3.7 :-) (see the videos from the recent Pycon).

My recommendation is that you rename self.logfile_out to self.log_file_name to keep things clear. I would rewrite as:

if self.log_file_name:
        self._of = open(self.log_file_name, mode='w', encoding='utf-8')
OTPSkipper

It was something stupid. Spelled the reference to the file Handel wrong.

Thanks!!