Searching a directory for folders and files using python
30,134
You have to join the current directory and the name to get the absolute path to a file:
for root, dirs, files in os.walk(apkLocation + apkFolder):
for name in files:
if name.endswith(("lib", ".so")):
os.path.join(root, name)
It's documented here http://docs.python.org/3/library/os.html#os.walk, too.
Author by
DesperateLearner
Updated on March 05, 2021Comments
-
DesperateLearner about 3 years
I have a directory structure like the one given below.
MainFolder | [lib] / | \ [A] [B] [C] -- file1.so | | file2.so file1.so file1.so file2.so file2.so
I'm trying to look for the 'lib' folder in that structure which might not be there at times. So I'm using the following to check for the presence of the 'lib' folder:
if os.path.isdir(apkLocation + apkFolder + '/lib/'):
If lib folder exists, then I carry on to search the folders inside 'lib'. I have to store the names of the folder A,B and C and look for the files ending with '.so' whose path should be stored as /lib/A/file1.so,/lib/A/file2.so and so on.
if os.path.isdir(apkLocation + apkFolder + '/lib/'): for root, dirs, files in os.walk(apkLocation + apkFolder): for name in files: if name.endswith(("lib", ".so")): print os.path.abspath(name)
This gives me an out
file1.so file2.so file1.so file2.so file1.so file2.so
Desired output:
/lib/A/file1.so /lib/A/file2.so /lib/B/file1.so /lib/B/file2.so /lib/C/file1.so /lib/C/file2.so
and also the folders A,B and C are to be saved separately.
-
DesperateLearner over 10 yearsThat worked :) How do I retrieve the folder A,B and C instead of playing around with string functions on the output of os.path.join(root,name)? Any path functions that does this?
-
DesperateLearner over 10 yearsThis did it os.path.join(root,name).replace(apkLocation+apkFolder+'/lib','')
-
Christian Heimes over 10 yearsYou are looking for os.path.split() and maybe os.path.dirname(). It's all well documented, too.