使用Python检查目录是否包含文件
在Python中查找目录是否为空可以使用os库的listdir()
方法来实现。 Python中的 OS 模块提供了与操作系统交互的功能。该模块提供了一种使用操作系统相关功能的可移植方式。
Syntax: os.listdir(
Returns: A list of files present in the directory, empty list if the directory is empty
现在通过调用listdir()
方法,我们可以获得目录中所有文件的列表。要检查目录的空性,我们应该检查返回列表的空性。我们有很多方法可以做到这一点,让我们一一检查。
- 通过将返回的列表与硬编码的空列表进行比较
空列表可以写为[]
。所以我们可以将返回列表的相等性与[]
进行比较。# Python program to check # if a directory contains file import os # path of the directory directoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Comparing the returned list to empty list if os.listdir(directoryPath) == []: print("No files found in the directory.") else: print("Some files found in the directory.")
输出:
Some files found in the directory.
- 通过将返回列表的长度与 0 进行比较
我们可以使用Python的len()
方法获取列表的长度。如果返回列表的长度为零,则目录为空,否则为空。# Python program to check if # a directory contains file import os # path of the directory directoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Checking the length of list if len(os.listdir(directoryPath)) == 0: print("No files found in the directory.") else: print("Some files found in the directory.")
输出:
Some files found in the directory.
- 通过比较列表的布尔值
在上述方法中,我们使用了列表长度的显式比较。现在我们正以一种更 Pythonic 的方式使用真值测试。空列表在Python中被评估为 False。# Python program to check if # a directory is empty import os # path of the directory directoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Checking the boolean value of list if not os.listdir(directoryPath): print("No files found in the directory.") else: print("Some files found in the directory.")
输出:
Some files found in the directory.
完整的源代码:
# Python program to check if
# the directory is empty
import os
# Function for checking if the directory
# containes file or not
def isEmpty(directoryPath):
# Checking if the directory exists or not
if os.path.exists(directoryPath):
# Checking if the directory is empty or not
if len(os.listdir(directoryPath)) == 0:
return "No files found in the directory."
else:
return "Some files found in the directory."
else:
return "Directory does not exist !"
# Driver's code
# Valid directory
directoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil"
print("Valid path:", isEmpty(directoryPath))
# Invalid directory
directoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil/GeeksforGeeks"
print("Invalid path:", isEmpty(directoryPath))
输出:
Valid path: Some files found in the directory.
Invalid path: Directory does not exist !