Python - how to find files and skip directories in os.listdir

依然范特西╮ 提交于 2019-11-26 06:37:51

问题


I use os.listdir and it works fine, but I get sub-directories in the list also, which is not what I want: I need only files.

What function do I need to use for that?

I looked also at os.walk and it seems to be what I want, but I\'m not sure of how it works.


回答1:


You need to filter out directories; os.listdir() lists all names in a given path. You can use os.path.isdir() for this:

basepath = '/path/to/directory'
for fname in os.listdir(basepath):
    path = os.path.join(basepath, fname)
    if os.path.isdir(path):
        # skip directories
        continue

os.walk() does the same work under the hood; unless you need to recurse down subdirectories, you don't need to use os.walk() here.




回答2:


Here is a nice little one-liner in the form of a list comprehension:

[f for f in os.listdir(your_directory) if os.path.isfile(os.path.join(your_directory, f))]

This will return a list of filenames within the specified your_directory.




回答3:


import os
directoryOfChoice = "C:\\" # Replace with a directory of choice!!!
filter(os.path.isfile, os.listdir(directoryOfChoice))

P.S: os.getcwd() returns the current directory.




回答4:


for fname in os.listdir('.'):
    if os.path.isdir(fname):
       pass  # do your stuff here for directory
    else:
       pass  # do your stuff here for regular file


来源:https://stackoverflow.com/questions/22207936/python-how-to-find-files-and-skip-directories-in-os-listdir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!