Pick the file with the shortest name

Question:

I want to find the .txt file with the shortest name inside a folder.

import glob
import os

inpDir = "C:/Users/ft/Desktop/Folder"

os.chdir(inpDir)

for file in glob.glob("*.txt"):
    l = len(file)

For the moment I found the length of the str of the name, how can I return the shortest name?
Thanks

Asked By: Joss Fres

||

Answers:

To find the shortest file just compare to the current shortest:

chosen_file = ""

for file in glob.glob("*.txt"):
    if chosen_file == "" or len(file) < len(chosen_file):
        chosen_file = file

print(f"{chosen_file} is the shortest file")

Once you’ve finished the loop, the chosen_file str is guaranteed to be the shortest.

Answered By: scr
min = 1000

for file in glob.glob("*.txt"):
    if len(file) < min:
        min = len(file)
        name = file
Answered By: rtoth

Cleaner to put it in a function and calling it:


import glob
import os

def shortest_file_name(inpDir: str, extension: str) -> str:
    os.chdir(inpDir)
    shortest, l = '', 0b100000000
    for file in glob.glob(extension):
        if len(file) < l:
            l = len(file)
            shortest = file
    return shortest

inpDir = "C:/Users/ft/Desktop/Folder"
min_file_name = shortest_file_name(inpDir, "*.txt")
Answered By: Guillaume BEDOYA

Just use glob module to get a list of files, and then utilize min(..., key=...) to find the shortest string (see help(min)):

min(glob.glob('*.txt'), key=len)
Answered By: Klas Š.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.