How to list only regular files (excluding directories) in a directory in Python

Can be used os.listdir('somedir')

to get all files under somedir

. However, if I only want regular files (excluding directories) as the result find . -type f

under the shell.

I know what can be used [path for path in os.listdir('somedir') if not os.path.isdir('somedir/'+path)]

to achieve a similar result as in this related question: How to list only top level directories in Python? ... Just wondering if there are more concise ways to do this.

+3


source to share


3 answers


You can use os.walk

that returns a tuple of path, folders, and files:



files = next(os.walk('somedir'))[2]

      

+7


source


I have several ways in which I accomplish such tasks. I cannot comment on the brief nature of the decision. FWIW here they are:

1.the code below will contain all files that end in .txt. you can remove the ".endswith" part

import os
for root, dirs, files in os.walk('./'): #current directory in terminal
     for file in files:
             if file.endswith('.txt'):
             #here you can do whatever you want to with the file.

      



2.This code here assumes the path is provided to the function and will add all the .txt files to the list, and if there are subdirectories in the path, it will add those files to subdirectories to the subfiles

def readFilesNameList(self, path):
    basePath = path
    allfiles = []
    subfiles = []
    for root, dirs, files in os.walk(basePath):
      for f in files:
         if f.endswith('.txt'):
             allfiles.append(os.path.join(root,f))
             if root!=basePath:
                 subfiles.append(os.path.join(root, f))

      

I know the code is just skeletal in nature, but I think you can get the big picture.
if you find a laconic way! :)

+3


source


The earlier answer is os.walk

perfect if you only want files in the top level directory. If you also want subdirectory files (a la find

) you need to process each directory like:

def find_files(path):
    for prefix, _, files in os.walk(path):
        for name in files:
            yield os.path.join(prefix, name)

      

Now list(find_files('.'))

this is a list of the same it find . -type f -print

would give you ( list

because find_files is a generator if it isn't obvious).

0


source







All Articles