Lets say I want to find the youngest/newest *.txt file inside a folder, for example /tmp/? I wrote this little python script for this, but are there better ways to do it?

By youngest I mean the file with the least recent change or creation date? All files have these timestamps. But could I also watch the filesystems folder for file creation events?

import os
import glob

def find_newest_file_type(glob_path):
    # youngest file has biggest timestamp
    youngest = -10
    ultpath = "file_does_not_exist0xfadfadsfadfads.asdfajsdklfj"
    for file in  glob.iglob(glob_path):
        mtime = os.path.getmtime(file)
        if mtime > youngest:
            youngest = mtime
            ultpath = file
    return ultpath

newest = find_newest_file_type("/tmp/*.txt")
  • scratsearcher 🔍🔮📊🎲@sopuli.xyzOP
    link
    fedilink
    English
    arrow-up
    1
    ·
    1 month ago

    Thanks, with maxdepth 1 it works without errors!


    Since the step of finding the youngest file in the folder is part of a larger more complicated workflow/pipeline for me (transcribe the youngest wav file in the tmp folder, name the resulting transcript after the youngest file in the …/recordings_folder/ and copy it there) I will need to integrate it into a python script I think.

    • dandelion (she/her)@lemmy.blahaj.zone
      link
      fedilink
      English
      arrow-up
      2
      ·
      edit-2
      1 month ago

      sure, you could probably also do all those other things in bash too, but you could do it all in python as well 😁

      I tend to use bash more for manipulating files and directories. I would probably write a bash script for all the stuff you’re doing.

      I would probably use python for more complicated logic or when python has some library that lets me do something bash doesn’t easily do.

      Finding and moving files is easy in bash, but automating making changes to an Excel sheet is very difficult to do with bash, so I would use Python to automate changes to an Excel file, for example. There are libraries that exist in python you can import and use for that kind of task.

      Recommended reading: