Reputation: 20929
One can use os.listdir('somedir')
to get all the files under somedir
. However, if what I want is just regular files (excluding directories) like the result of find . -type f
under shell.
I know one can use [path for path in os.listdir('somedir') if not os.path.isdir('somedir/'+path)]
to achieve similar result as in this related question: How to list only top level directories in Python?. Just wondering if there are more succinct ways to do so.
Upvotes: 3
Views: 4551
Reputation: 316
I have a couple of ways that i do such tasks. I cannot comment on the succinct nature of the solution. FWIW here they are:
1.the code below will take all files that end with .txt. you may want to 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 will assume that the path is provided to the function and will append all .txt files to a list and if there are subdirectories in the path, it will append those files in the subdirectories to 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 general picture.
post if you find the succinct way! :)
Upvotes: 3
Reputation: 489748
The earlier os.walk
answer is perfect if you only want the files in the top-level directory. If you want subdirectories' files too, though (a la find
), you need to process each directory, e.g.:
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('.'))
is a list of the same thing find . -type f -print
would have given you (the list
is because find_files is a generator, in case that's not obvious).
Upvotes: 0
Reputation: 53879
You could use os.walk
, which returns a tuple of path, folders and files:
files = next(os.walk('somedir'))[2]
Upvotes: 7