A
A
Alexander Y2016-05-20 11:10:46
Python
Alexander Y, 2016-05-20 11:10:46

Python: how to check if there are any files in a directory?

Please tell me how to use Python to check if there are any files in a certain directory without specifying exactly which ones (without specifying names or extensions). Interested in simply the fact of the presence or absence of something. It is desirable so that the script execution does not stop on an error, but gives a log ("files are present" / "absent").

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2016-05-20
@Chudilka

import os

if os.listdir(path):
    #Есть файлы
else:
    #Нет файлов

E
Error 502, 2016-05-20
@NullByte

import os
os.listdir(path) - displays a list of all files in the current folder
len(os.listdir(path)) - if there are files, it should return a value other than 0, because the list is not empty in this case. If there are no files or subdirectories, it will return 0.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question