如何使用python 3检查文件夹是否包含文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25675352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check to see if a folder contains files using python 3
提问by Heather
I've searched everywhere for this answer but can't find it.
我到处搜索这个答案,但找不到。
I'm trying to come up with a script that will search for a particular subfolder then check if it contains any files and, if so, write out the path of the folder. I've gotten the subfolder search part figured out, but the checking for files is stumping me.
我试图想出一个脚本来搜索特定的子文件夹,然后检查它是否包含任何文件,如果是,写出文件夹的路径。我已经弄清楚了子文件夹搜索部分,但是文件检查让我很困惑。
I have found multiple suggestions for how to check if a folder is empty, and I've tried to modify the scripts to check if the folder is not empty, but I'm not getting the right results.
我找到了关于如何检查文件夹是否为空的多个建议,并且我尝试修改脚本以检查文件夹是否为空,但我没有得到正确的结果。
Here is the script that has come the closest:
这是最接近的脚本:
for dirpath, dirnames, files in os.walk('.'):
if os.listdir(dirpath)==[]:
print(dirpath)
This will list all subfolders that are empty, but if I try to change it to:
这将列出所有空的子文件夹,但如果我尝试将其更改为:
if os.listdir(dirpath)!=[]:
print(dirpath)
it will list everything--not just those subfolders containing files.
它将列出所有内容——而不仅仅是那些包含文件的子文件夹。
I would really appreciate it if someone could point me in the right direction.
如果有人能指出我正确的方向,我将不胜感激。
This is for Python 3.4, if that matters.
如果这很重要,这适用于 Python 3.4。
Thanks for any help you can give me.
感谢你给与我的帮助。
采纳答案by tdelaney
'files' already tells you whats in the directory. Just check it:
'files' 已经告诉你目录中的内容。只需检查一下:
for dirpath, dirnames, files in os.walk('.'):
if files:
print(dirpath, 'has files')
if not files:
print(dirpath, 'is empty')
回答by ventsyv
entities = os.listdir(dirpath)
for entity in entities:
if os.path.isfile(entity):
print(dirpath)
break
回答by Jon Clements
You can make use of the new pathliblibrary introduced in Python 3.4 to extract all non-empty subdirectories recursively, eg:
您可以利用pathlibPython 3.4 中引入的新库递归提取所有非空子目录,例如:
import pathlib
root = pathlib.Path('some/path/here')
non_empty_dirs = {str(p.parent) for p in root.rglob('*') if p.is_file()}
Since you have to walk the tree anyway, we build a set of the parent directories where a file is present which results in a set of directories that contain files - then do as you wish with the result.
由于无论如何您都必须遍历树,因此我们构建了一组存在文件的父目录,这会导致一组包含文件的目录 - 然后按照您的意愿处理结果。
回答by user
If you can delete the directory, you can use this:
如果可以删除目录,则可以使用以下命令:
my_path = os.path.abspath("something")
try:
os.rmdir(my_path)
is_empty = True
# Do you need to keep the directory? Recreate it!
# os.makedirs(my_path, exist_ok=True)
except OSError:
is_empty = False
if is_empty:
pass
The os.rmdironly removes a directory if it is empty, otherwise it throws the OSError exception.
该os.rmdir只删除一个目录,如果它是空的,否则它抛出OSERROR例外。
You can find a discussion about this on:
您可以在以下位置找到有关此问题的讨论:
For example, deleting an empty directory is fine when you are planing to do a git clone, but not if you are checking beforehand whether the directory is empty, so your program does not throw an empty directory error.
例如,当您计划执行 git clone 时删除一个空目录是可以的,但如果您事先检查目录是否为空,则删除一个空目录就没有问题,因此您的程序不会抛出空目录错误。
回答by Ammar Alyousfi
You can use this simple code:
您可以使用这个简单的代码:
dir_contents = [x for x in os.listdir('.') if not x.startswith('.')]
if len(dir_contents) > 0:
print("Directory contains files")
It checks for files and directoriesin the current working directory (.). You can change .in os.listdir()to check any other directory.
它检查当前工作目录 ( )中的文件和目录.。您可以更改.在os.listdir()检查任何其他目录。
回答by Prayson W. Daniel
Adding to @Jon Clements' pathlib answer, I wanted to check if the folder is empty with pathlib but without creating a set:
添加到@Jon Clements 的 pathlib 答案中,我想使用 pathlib 检查文件夹是否为空,但不创建集合:
from pathlib import Path
# shorter version from @vogdb
is_empty = not any(Path('some/path/here').iterdir())
# similar but unnecessary complex
is_empty = not bool(sorted(Path('some/path/here').rglob('*')))
vogdb method attempts iterates over all files in the given directory. If there is no files, any() will be False. We negate it with not so that is_empty is True if no files and False if files.
vogdb 方法尝试遍历给定目录中的所有文件。如果没有文件,any() 将为 False。我们用 not 否定它,所以 is_empty 如果没有文件则为 True,如果有文件则为 False。
sorted(Path(path_here).rglob('*')) return a list of sorted PosixPah items. If there is no items, it returns an empty list, which is False. So is_empty will be True if the path is empty and false if the path have something
sorted(Path(path_here).rglob('*')) 返回已排序 PosixPah 项目的列表。如果没有项目,则返回一个空列表,即 False。因此,如果路径为空,则 is_empty 将为 True,如果路径有内容则为 false
Similar idea results {} and [] gives the same:

类似的想法结果 {} 和 [] 给出了相同的结果:

回答by mab
You can directly use the generator instead of converting to a set or (ordered) list first:
您可以直接使用生成器,而不是先转换为集合或(有序)列表:
from pathlib import Path
p = Path('abc')
def check_dir(p):
if not p.exists():
print('This directory is non-existent')
return
try:
next(p.rglob('*'))
except StopIteration:
print('This directory is empty')
return
print('OK')
回答by Gavriel Cohen
Check is folder contains files:
检查文件夹是否包含文件:
import os
import shutil
if len(os.listdir(folder_path)) == 0: # Check is empty..
shutil.rmtree(folder_path) # Delete..
回答by alper
I have follews Bash checking if folder has contentsanswer.
我跟随Bash 检查文件夹是否有内容答案。
os.walk('.')returns the complete files under a directory and if there thousands it may be inefficient. Instead following command find "$target" -mindepth 1 -print -quitreturns first found file and quits. If it returns an empty string, which means folder is empty.
os.walk('.')返回目录下的完整文件,如果有数千个,则效率可能很低。相反,以下命令find "$target" -mindepth 1 -print -quit返回第一个找到的文件并退出。如果它返回一个空字符串,这意味着文件夹是空的。
You can check if a directory is empty using
find, and processing its output
您可以使用
find,检查目录是否为空,并处理其输出
def is_dir_empty(absolute_path):
cmd = ["find", absolute_path, "-mindepth", "1", "-print", "-quit"]
output = subprocess.check_output(cmd).decode("utf-8").strip()
return not output
print is_dir_empty("some/path/here")
回答by Praveen Kulkarni
With pathlibthis can be done as follows:
随着pathlib这是可以做到如下:
import pathlib
# helper function
def is_empty(_dir: pathlib.PAth) -> bool:
return not bool([_ for _ in _dir.iterdir()])
# create empty dir
_dir = pathlib.Path("abc")
# check if dir empty
is_empty(_dir) # will retuen True
# add file s to folder and call it again

