【问题标题】:Pick the file with the shortest name选择名称最短的文件
【发布时间】:2022-11-29 22:32:54
【问题描述】:

我想在文件夹中找到名称最短的 .txt 文件。

import glob
import os

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

os.chdir(inpDir)

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

目前我找到了名称 str 的长度,如何返回最短的名称? 谢谢

【问题讨论】:

  • 取变量 l 的最小值

标签: python


【解决方案1】:

只需取 l 中的最小值:

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

【讨论】:

    【解决方案2】:

    要找到最短的文件,只需与当前最短的文件进行比较:

    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")
    
    

    完成循环后,chosen_file str 保证是最短的。

    【讨论】:

      【解决方案3】:
      min = 1000
      
      for file in glob.glob("*.txt"):
          if len(file) < min:
              min = len(file)
              name = file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多