Python 脚本 grep 目录

标签 python linux bash shell unix

我有一个来自 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!"

关于Python 脚本 grep 目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28944991/

相关文章:

git - Git Bash 和 GitHub for Windows shell 有什么区别?

散点图中的 Python Matplotlib 线

python - Nose:基于 TestCase 的类的生成器

linux - 运行 Contiki 教程时出现 "Not a git repository:"错误消息

c - SIG_IGN, SIG_DFL, SIG_ERR 的定义

bash - 如何测试一个变量以bash中的字符串开头?

bash - 从 bash 到 `function` 的 fish shell 和执行程序

python - 生成器未按预期运行

python - 如何使用 epoll 和 python 3.1 进行异步 http 请求

linux - logrotate 非 .log