简体   繁体   English

Python中有没有办法找到名称中数字最小的文件?

[英]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. *score*是一个浮点数,我需要在另一个脚本中识别文件夹中编号最小的文件。 Example:例子:

name_123.12
name_145.45

This should return string "name_123.12"这应该返回字符串“name_123.12”

min takes a key function. min接受一个关键函数。 You can use that to define the way min is calculated:您可以使用它来定义min的计算方式:

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.只是想说 Mark Meyer 完全正确,但您还提到您正在从目录中读取这些文件名。 In that case, there is a bit of code you could add to Mark's answer:在这种情况下,您可以在 Mark 的回答中添加一些代码:

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!扩展了蒂姆·比格莱森的回答,谢谢蒂姆!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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