2

How can I check if ANY file exists in a certain folder? I know how to check A file. which is as follows

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

Thanks in advance

TheTechGuy
  • 1,568
  • 4
  • 18
  • 45

3 Answers3

7

use os.listdir

Ex:

import os

if os.listdir(path):
    print("file is there")
else:
    print("not found")
Rakesh
  • 81,458
  • 17
  • 76
  • 113
3

will list the files in the folder folder script is running from main

folder
  files
  ...
  main.py

will list only files, not . and ..

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))]
shahaf
  • 4,750
  • 2
  • 29
  • 32
2
folder = os.listdir("/home/yourname/yourdir")
if len(folder)>0:
    print "the folder is not empty"
Lupanoide
  • 3,132
  • 20
  • 36