Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - ignore directory in os.listdir()

I have the following snippet -

runbooksrc_files = os.listdir(runbooksrc)
for file_name in runbooksrc_files:
    full_file_name = os.path.join(runbooksrc, file_name)
    if (os.path.isfile(full_file_name)):
        shutil.copy(full_file_name, runbookdest)
        logging.info ("copying " + file_name)
    else:
        logging.warning ("unable to copy " + file_name)
        sys.exit(2)

It's failing because in the directory is another sub-directory which I want it to ignore. How do I go about telling os.listdir to ignore directories when doing the list?

like image 663
whoisearth Avatar asked Mar 02 '26 09:03

whoisearth


1 Answers

You could filter the list before going through it.

runbooksrc_files = [i for i in os.listdir(runbooksrc) if not os.path.isdir(i)]
like image 78
Farmer Joe Avatar answered Mar 04 '26 22:03

Farmer Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!