Created
January 15, 2025 20:30
-
-
Save rdermer/2b04239fdb05e27b9c322e8a75d15817 to your computer and use it in GitHub Desktop.
Latest filename from directory or list of files - whitespace safe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
import os | |
# prints name of newest file - ignores directories | |
# 3 cases | |
# list of files | |
# a single argument that is a directory | |
# no arguments - the current directory | |
def append_slash_if_missing(dir_path): | |
"""Appends a slash to the directory path if it's missing.""" | |
if dir_path and dir_path[-1] != os.path.sep: | |
dir_path += os.path.sep | |
return dir_path | |
def main(): | |
if len(sys.argv) > 2: | |
# a lit of files | |
listToProcess = sys.argv[1:] | |
elif len(sys.argv) == 2: | |
if os.path.isdir(sys.argv[1]): | |
dir = append_slash_if_missing(sys.argv[1]) | |
listToProcess = [ dir + item for item in os.listdir(dir) ] | |
else: | |
listToProcess = sys.argv[1:] | |
else: | |
listToProcess = os.listdir(".") | |
newest_file = None | |
newest_time = 0 | |
for filename in listToProcess: | |
#print(f"FILENAME {filename}") | |
if os.path.isfile(filename): | |
file_time = os.path.getmtime(filename) | |
if file_time > newest_time: | |
newest_time = file_time | |
newest_file = filename | |
if newest_file: | |
print(f"{newest_file}") | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment