10 examples of 'python check if directory is empty' in Python

Every line of 'python check if directory is empty' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
44def empty(self):
45 if self.exists:
46 for root, directories, files in walk(self.path):
47 for d in directories[:]:
48 if not d.startswith(('.', '_')):
49 Directory(abspath(root, d)).rm()
50
51 directories.remove(d)
52
53 for f in files:
54 if not f.startswith(('.', '_')):
55 File(abspath(root, f)).rm()
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

21def check_dir(folder):
22 # Check if a folder already exists, if not return the value True.
23 import os
24 import sys
25
26 if os.path.exists(folder):
27 if not os.listdir(folder):
28 return False
29 else:
30 print('Folder: <%s> already exists. Program aborted.' % folder)
31 sys.exit()
32 else:
33 return True
25def valid_directory(dir_path):
26 if not os.path.exists(dir_path):
27 print(dir_path + ' does not exist.')
28 return False
29 if not os.path.isdir(dir_path):
30 print(dir_path + ' is not a directory.')
31 return False
32 return True
23def test_check_is_file_empty_when_file_doesnt_exist(self):
24 with self.assertRaisesRegex(
25 FileNotFoundError,
26 r"^Path 'file_that_doesnt_exist.txt' doesn't exist$"):
27 check_is_file_empty('file_that_doesnt_exist.txt')
8def test_check_is_file_empty_when_file_is_empty(self):
9 # Create a file for the test
10 with open('testemptyfile.txt', 'w'):
11 pass
12
13 self.assertTrue(check_is_file_empty('testemptyfile.txt'))
14 os.remove('testemptyfile.txt')
25def assert_dir(path):
26 if not (os.path.isdir(path)):
27 fatal("Error: Directory '%s' not found." % path)
16def isdir(dirname):
17 return os.path.isdir(dirname)
400def DeleteEmptyDirList(self, fileList):
401 for file in fileList:
402 self.DeleteEmptyDir(file)
14def dir_exists(path: str) -> bool:
15 """Return whether the specified path leads to a directory."""
16 return Path(path).is_dir()
52def verify_directory(dir):
53 """create and/or verify a filesystem directory."""
54
55 tries = 0
56
57 while not os.path.exists(dir):
58 try:
59 tries += 1
60 os.makedirs(dir, compat.octal("0775"))
61 except:
62 if tries > 5:
63 raise

Related snippets