Python: 如何找到与字符串中前 3 个字符匹配的目录?

Python: How can i find a directory that matches the first 3 characters from a string?

我有一个包含 50 多个目录的目录,其中的目录名为 "XXX - something"

如果我有X = '123' 如何找到以'123'开头的目录?

import os, sys
folder = sys.argv[1]

folders = "ls -lh %s*" %(folder) 
os.system(folders)

运行 代码由 folderseach.py 123

其中 123 代表您要查找的文件夹

您可以尝试使用 os.walk

import os
[i[0] for i in os.walk('/path/to/directory/') if i[0].split("/")[-1].startswith(X)]

如果文件夹名称以X (your varibale)

开头,它将在文件夹/path/to/directory/中递归return一个list

[i for i,j,k in os.walk('/path/to/directory/') if i.split("/")[-1].startswith(X)]