python-忽略os.listdir()中的目录

python-忽略os.listdir()中的目录,python,python-2.7,Python,Python 2.7,我有以下片段- 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.in

我有以下片段-

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)

它失败了,因为目录中有另一个子目录,我希望它忽略它。如何告诉os.listdir在创建列表时忽略目录?

您可以在查看列表之前对其进行筛选

runbooksrc_files = [i for i in os.listdir(runbooksrc) if not os.path.isdir(i)]
以下是答案-

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)

扫描文件夹后,请在复制之前检查它是否为文件。

thnx。事实上,我找到了答案并发布了帖子,但你也是正确的,所以我会在11分钟内给你分数,当我可以接受它时:)