【问题标题】:how to check if ANY file exists in a certain folder with python? [duplicate]如何使用python检查某个文件夹中是否存在任何文件? [复制]
【发布时间】:2018-04-23 12:52:15
【问题描述】:

如何检查某个文件夹中是否存在任何文件?我知道如何检查 A 文件。如下

a = os.path.exists("text.txt")
if a:
    print("file is there")
else:
    print("not found")

提前致谢

【问题讨论】:

标签: python


【解决方案1】:

使用os.listdir

例如:

import os

if os.listdir(path):
    print("file is there")
else:
    print("not found")

【讨论】:

    【解决方案2】:

    将列出文件夹folder中的文件 脚本从main运行

    folder
      files
      ...
      main.py
    

    将仅列出文件,而不是 ...

    import os
    dir = os.path.dirname(__file__) or '.'
    dir_path = os.path.join(dir, '../folder/')
    onlyfiles = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]
    

    【讨论】:

    • 谢谢,感谢您的帮助
    【解决方案3】:
    folder = os.listdir("/home/yourname/yourdir")
    if len(folder)>0:
        print "the folder is not empty"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-09
      • 2018-11-17
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 2016-05-04
      • 2011-11-15
      相关资源
      最近更新 更多