1

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,468
  • 2
  • 17
  • 41

3 Answers3

6

use os.listdir

Ex:

import os

if os.listdir(path):
    print("file is there")
else:
    print("not found")
Rakesh
  • 78,594
  • 17
  • 67
  • 103
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,442
  • 2
  • 25
  • 31
2
folder = os.listdir("/home/yourname/yourdir")
if len(folder)>0:
    print "the folder is not empty"
Lupanoide
  • 2,962
  • 20
  • 33