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
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.
min = 1000
for file in glob.glob("*.txt"):
if len(file) < min:
min = len(file)
name = file
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")
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)
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
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.
min = 1000
for file in glob.glob("*.txt"):
if len(file) < min:
min = len(file)
name = file
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")
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)