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")
yes,
find
does look at sub-directories - sorry, I didn’t realize you only wanted it to search in the current dir only and not in sub-directories. You would add-maxdepth 1
to thefind
command to tell it to only look in the current dir, not further.EDIT: and yeah, I would recommend doing tasks like this in bash - you can just type them directly into the terminal. The convenience of writing one-liners like this from memory is hard to beat.
Once you have enough experience you can just do it from memory, it’s all accessible. Writing a python program and running it every time you want to do a small task like finding the newest file is overkill IMO. But it can be nice to have a little cheatsheet file of bash oneliners you have written in the past to refer to later, esp. as a beginner.
That said, it’s not wrong to take what I would see as the less convenient route by writing a python script - it can be fun to learn both, and it’s more useful to use python if you need to automate a more complicated task or need that newest file as a part of a larger program you’re writing in python.
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.
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: