IF 语句:Shell 到 python

IF statement : Shell to python

假设

DIR2 = /tmp/test'
'dirName = stats

if [ -d /$DIR2/$dirName/* ]

以上是我的。 它检查 /tmp/test/stats 目录是否包含其中的任何文件或目录。 如果它确实包含某些内容,那么我将打印出 yes。

如何将其翻译成 python 语言?

if os.path.exists(DIR2 + "/" + dirName + ):
    print "pass"

到目前为止我尝试过的是..

但我知道我需要在 if 语句的末尾多一个词。

我想最简单的方法是检查 os.listdir 返回的列表是否为非空...

if os.listdir(os.path.join(DIR2, dirName)):
    print("Not empty!")

我相信这可以满足您的需求,而无需在目录中创建包含整组文件名的列表。

hasContents = False
for (root, dirs, files) in os.walk(DIR2 + "/" + dirName):
    if dirs or files:
        hasContents = True
    break