简体   繁体   English

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

[英]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? 在执行列表时,如何告诉os.listdir忽略目录?

您可以在浏览列表之前对其进行过滤。

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

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. 扫描文件夹后,检查是否是文件,然后再进行复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM