Python Forum
How to save latest time stamp in a file?
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to save latest time stamp in a file?
#9
Did look more this so i did write an improved version,battle tested in Windows and Linux.
Now do a recursive scan in folder with pathlib, os.walk in combination with glob.
So now can choice to watch all files or only a file extension eg deb, txt, jpg, ect...
The setup has been made easy.
# watch_folder.py
import os, sys
import platform
import logzero
from logzero import logger
from pathlib import Path, PurePath
 
def newest_file(folder_to_watch, file_extension):
    if file_extension == '*':
        fn = []
        for root, dirs, files in os.walk(folder_to_watch):
            for file in files:
                fn.append(os.path.join(root, file))
        try:
            return max(fn, key=os.path.getctime)
        except ValueError:
            print('No file in folder')
            sys.exit()
    else:
        paths = []
        for filename in Path(folder_to_watch).glob(f'**/*.{file_extension}'):
            paths.append(filename)
        try:
            return max(paths, key=os.path.getctime)          
        except ValueError:
            print(f'No file with extension <{file_extension}>')
            sys.exit()
 
def stamp(newest_file):
    file_stamp = os.path.getmtime(newest_file)
    return file_stamp, newest_file
 
def file_compare(file_stamp, file_name, log_folder):
    # 3 rotations, each with a maximum filesize of 1MB
    logzero.logfile(f"{log_folder}logfile.log",
        maxBytes=1e6, backupCount=3, disableStderrLogger=True)
    try:
        with open(f'{log_folder}stamp.txt') as f:
            old_stamp = float(f.read())
        if old_stamp == file_stamp:
            print(f'No change: {file_name} --> {file_stamp}')
        else:
            print(f'New file: {repr(file_name)} --> {file_stamp}')
            logger.info(f'{file_name} --> {file_stamp}')
            with open(f'{log_folder}stamp.txt', 'w') as f:
                f.write(str(file_stamp))
    except OSError:
        with open(f'{log_folder}stamp.txt', 'w') as f:
            f.write(str(file_stamp))
 
if __name__ == '__main__':
    #--- Setup ---#
    folder_to_watch = '/home/tom/Documents/test_folder/'
    # Watch a spesific file extensions,eg txt, jpg, zip, ect...
    # All files default *
    file_extension = '*'
    # Folder to save filestamp and log file
    log_folder = '/home/tom/Documents/stamp/'
    #---#
    newest_file = newest_file(folder_to_watch, file_extension)
    file_stamp = stamp(newest_file)[0]
    file_name = os.path.basename(stamp(newest_file)[1])
    #--- Start ---#
    file_compare(file_stamp, file_name, log_folder)
For and all Python schedule solution can use schedule.
import subprocess
import schedule
import time
 
def watch_folder():
    subprocess.run(['python', 'watch_folder.py'])
 
if __name__ == '__main__':
    schedule.every(.1).minutes.do(watch_folder)
    while True:
        schedule.run_pending()
        time.sleep(1)
So can call it a very lite version of watchdog.
Watchdog handles many filesystem events and can also execute shell command.
Reply


Messages In This Thread
RE: How to save latest time stamp in a file? - by snippsat - Jul-01-2019, 11:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Open/save file on Android frohr 0 412 Jan-24-2024, 06:28 PM
Last Post: frohr
  how to save to multiple locations during save cubangt 1 630 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  Filename stamp script is needed ineuw 11 4,822 Sep-12-2023, 03:05 AM
Last Post: ineuw
  save values permanently in python (perhaps not in a text file)? flash77 8 1,362 Jul-07-2023, 05:44 PM
Last Post: flash77
  Save and Close Excel File avd88 0 3,325 Feb-20-2023, 07:19 PM
Last Post: avd88
  Save multiple Parts of Bytearray to File ? lastyle 1 1,018 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  How to map by time stamp and name SriRajesh 0 1,207 Apr-09-2022, 12:49 PM
Last Post: SriRajesh
Sad Want to Save Print output in csv file Rasedul 5 11,361 Jan-11-2022, 07:04 PM
Last Post: snippsat
  Get latest version off website and save it as variable [SOLVED] AlphaInc 5 2,108 Nov-14-2021, 09:00 PM
Last Post: DeaD_EyE
  How to save Matplot chart to temp file? Morkus 2 4,653 Jun-12-2021, 10:52 AM
Last Post: Morkus

Forum Jump:

User Panel Messages

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