【问题标题】:Python - Choose directory that contains a specific stringPython - 选择包含特定字符串的目录
【发布时间】:2017-03-16 07:53:06
【问题描述】:

以下代码打印一个目录列表,这些目录恰好包含一个 3 字母代码,示例:

//Server/Jobs/2016\AAM - 'areallylongfilename'/

//Server/Jobs/2016\CLM - 'areallylongfilename'/

//Server/Jobs/2016\COO - 'areallylongfilename'/

import os
basepath = '//Server/Jobs/2016'
for fname in os.listdir(basepath):
    path = os.path.join(basepath, fname)
    if os.path.isdir(path):
        print(path)

如何根据 3 字母代码从列表中获取一个目录?

【问题讨论】:

  • 此代码不返回全部包含 3 个字母代码的目录列表,而是basepath 中存在的所有目录的路径。你的意思是从打印的路径中打印一条路径吗?如果是,任何特定路径或随机路径?
  • 是的,如果它包含我输入的 3 个字母代码,我想打印一个路径。我正在制作一个 Tkinter 应用程序,用于将文件从源移动到 //Server/Jobs/2016 路径中的目录之一。应用程序要求输入三字母代码以选择目标目录。

标签: python string directory contains listdir


【解决方案1】:
import os
basepath = '//Server/Jobs/2016'
asked_name = 'COO'
if len(asked_name) != 3:
        print "Expected 3 letter code, got:", asked_name
else:
        for fname in os.listdir(basepath):
                path = os.path.join(basepath, fname)
                if os.path.isdir(path):
                        if fname == asked_name:
                                print(path)

【讨论】:

  • 应该是if asked_name in fname。除此之外,谢谢!
【解决方案2】:

假设要扫描“d:”盘,可以编码为:

导入操作系统 目录=“d:\\” 对于 os.walk(dir) 中的根目录、目录和文件: 对于目录中的 a_dir: if ("Server" in a_dir) and ("Jobs" in a_dir) and ("2016" in a_dir): 打印 os.path.join(root,a_dir)

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 2021-12-01
    • 1970-01-01
    • 2014-07-04
    • 2015-10-17
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多