whoisearth
whoisearth

Reputation: 4170

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?

Upvotes: 3

Views: 4071

Answers (2)

whoisearth
whoisearth

Reputation: 4170

Here's the answer -

runbooksrc_files = os.listdir(runbooksrc)
for file_name in runbooksrc_files:
    if os.path.isfile(os.path.join(runbooksrc, file_name)):
        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)

After scanning the folder check if it's a file before doing the copy.

Upvotes: 0

Farmer Joe
Farmer Joe

Reputation: 6070

You could filter the list before going through it.

runbooksrc_files = [i for i in os.listdir(runbooksrc) if not os.path.isdir(i)]

Upvotes: 4

Related Questions