Python Forum
python file output to log file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python file output to log file
#3
With pathlib:
from pathlib import Path


def log(msg):
    cron_log = Path('/var/cron/log')
    with cron_log.open('r+') as log_fd:
        print(msg, file=log_fd)
Without pathlib
def log(msg):
    with open('/var/cron/log', 'r+') as log_fd:
        print(msg, file=log_fd)
A better solution is to use logging in Python: https://realpython.com/python-logging/#using-handlers
There are different solutions. You can create a handler to log to a file, you can log to syslog and systemd.
If you're not on Linux, you have lesser options.

The provided example has one problem. It opens the file, write to it and then the file is closed.
This happens for each message.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
python file output to log file - by Rsh - Aug-12-2019, 04:15 PM
RE: python file output to log file - by wavic - Aug-12-2019, 07:04 PM
RE: python file output to log file - by DeaD_EyE - Aug-12-2019, 08:48 PM
RE: python file output to log file - by Rsh - Aug-13-2019, 01:17 PM
RE: python file output to log file - by DeaD_EyE - Aug-13-2019, 09:00 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  python coding to run file NSR115 1 238 Jun-18-2024, 11:05 AM
Last Post: Kajalishu
  "[Errno 2] No such file or directory" (.py file) IbrahimBennani 13 868 Jun-17-2024, 12:26 AM
Last Post: AdamHensley
  Cannot get cmd to print Python file Schauster 11 777 May-16-2024, 04:40 PM
Last Post: xMaxrayx
  Can rich.logging output to file? pyfoo 1 499 Mar-21-2024, 10:30 AM
Last Post: pyfoo
  Python openyxl not updating Excel file MrBean12 1 543 Mar-03-2024, 12:16 AM
Last Post: MrBean12
  Python logging RotatingFileHandler writes to random file after the first log rotation rawatg 0 551 Feb-15-2024, 11:15 AM
Last Post: rawatg
  connect sql by python using txt. file dawid294 2 617 Jan-12-2024, 08:54 PM
Last Post: deanhystad
  file open "file not found error" shanoger 8 1,640 Dec-14-2023, 08:03 AM
Last Post: shanoger
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,900 Nov-09-2023, 10:56 AM
Last Post: mg24
  Replace a text/word in docx file using Python Devan 4 4,600 Oct-17-2023, 06:03 PM
Last Post: Devan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020