我有一个来自 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"
的目录(在本例中是 test1
和 test2
)
如果是,我想将 test1
和 test2
移动到其他目录。
谢谢
最佳答案
将os.listdir
与os.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/