[英]Python - Choose directory that contains a specific string
The following code prints a list of directories that all happen to contain a 3 letter code, Example: 以下代码显示所有碰巧都包含3个字母代码的目录列表,例如:
//Server/Jobs/2016\\AAM - 'areallylongfilename'/ //服务器/作业/ 2016 \\ AAM-'areallylongfilename'/
//Server/Jobs/2016\\CLM - 'areallylongfilename'/ //服务器/作业/ 2016 \\ CLM-'areallylongfilename'/
//Server/Jobs/2016\\COO - 'areallylongfilename'/ //服务器/作业/ 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)
How can I get one directory from the list based on the 3 letter code? 如何基于3个字母的代码从列表中获得一个目录?
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)
Suppose that you want to scan the "d:" disk, you can code as: 假设您要扫描“ d:”磁盘,可以将代码编写为:
import os dir="d:\\" for root,dirs,files in os.walk(dir): for a_dir in dirs: if ("Server" in a_dir) and ("Jobs" in a_dir) and ("2016" in a_dir): print os.path.join(root,a_dir)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.