简体   繁体   中英

Is there a way in Python to find a file with the smallest number in its name?

I have a bunch of documents created by one script that are all called like this:

name_*score*

*score* is a float and I need in another script to identify the file with the smallest number in the folder. Example:

name_123.12
name_145.45

This should return string "name_123.12"

min takes a key function. You can use that to define the way min is calculated:

files = [
    "name_123.12",
    "name_145.45",
    "name_121.45",
    "name_121.457"
]

min(files, key=lambda x: float((x.split('_')[1])))

# name_121.45

You can try get the number part first, and then convert it to float and sort. for example:

new_list = [float(name[5:]) for name in YOURLIST] # trim out the unrelated part and convert to float
result = 'name_' + str(min(new_list)) # this is your result

Just wanted to say Mark Meyer is completely right on this one, but you also mentioned that you were reading these file names from a directory. In that case, there is a bit of code you could add to Mark's answer:

import glob, os
os.chdir("/path/to/directory")
files = glob.glob("*")

print(min(files, key=lambda x: float((x.split('_')[1]))))

A way to get the lowest value by providing a directory.

import os
import re
import sys

def get_lowest(directory):
    lowest = sys.maxint
    for filename in os.listdir(directory):
        match = re.match(r'name_\d+(?:\.\d+)', filename)
        if match:
            number = re.search(r'(?<=_)\d+(?:\.\d+)', match.group(0))
            if number:
                value = float(number.group(0))
                if value < lowest:
                    lowest = value
    return lowest

print(get_lowest('./'))

Expanded on Tim Biegeleisen's answer, thank you Tim!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM