Python 脚本 greping 目录

Python Script greping directories

我有来自 Shell 脚本的 if 语句,并试图将其重新写入 python.. 但我不知道它在 python.

中是如何工作的

if [[ $(ls -d $DIR1/* | grep test) ]]

上面是 shell 脚本..我想用 python 语言重写它。 它的作用是查找以单词 "TEST" 开头的任何目录 在 DIR1 中,如果有,它应该执行 if..

中的命令

我该怎么做 python?

我会编辑问题.. 假设我的 DIR1/tmp/doc 并且在 /doc 目录中,有 test1、test2、get1、get2...

我想使用 if 语句来检查 /doc 目录中是否包含任何包含单词 "test" 的目录(在本例中为 test1test2 )

如果是,我想将 test1test2 移动到其他目录。

谢谢

os.listdiros.path.isdir结合使用:

path = 'YOUR/FOLDER'
# get all files in path
all_files = [os.path.join(path, f) for f in os.listdir(path) if f.startswith("test")]
# filter to keep only directories
folders = filter(os.path.isdir, all_files)

现在您可以使用空列表计算结果为 False:

if folders:
    print "has folders!"

您可以使用os.listdir获取目录中的所有内容,使用os.path.isdird.startswith("test")查找以"test"

开头的目录
import os
path = "/tmp/doc"

print([d for d in os.listdir(path)
   if os.path.isdir(os.path.join(d, path))
   and d.startswith("test")])

如果不区分大小写,请使用 d.lower().startswith("test")

移动使用shutil.move:

import os
import shutil

path = "/DIR1/"
test_dirs = (d for d in os.listdir(path)
       if os.path.isdir(os.path.join(d,path ))
       and d.startswith("test"))

for d in test_dirs:
    shutil.move(os.path.join(d,path),"your/dest/path")

或者在一个循环中完成所有操作:

for d in os.listdir(path):
    if os.path.isdir(os.path.join(d,path )) and d.startswith("test"):
        shutil.move(os.path.join(d, path), "your/dest/path")

要查找以 test 开头的目录,您只需使用 ls -d $DIR1/test*/

这是您的脚本的一个相对直接的等价物。请注意,您的 grep 不会检查目录是否实际上 以 'test' 开始 ,只是在任何地方都可以找到它,因此此代码执行相同的操作:

import os
import glob

DIR1 = 'dir1'
pattern = os.path.join(DIR1, '*')
if any(os.path.isdir(f) and 'test' in f for f in glob.glob(pattern)):
    do whatever