DanielTA
DanielTA

Reputation: 6558

Python equivalent to "find -type f"

What would be the equivalent in Python 3 to the bash command find -type f?

find /etc/ -type f

would generate a list that looks something like this:

/etc/rsyslog.conf
/etc/request-key.d/cifs.idmap.conf
/etc/request-key.d/id_resolver.conf
/etc/issue
/etc/maven/maven2-depmap.xml
/etc/gtkmathview/gtkmathview.conf.xml
/etc/fstab
/etc/machine-id
/etc/rpmlint/mingw-rpmlint.config
/etc/rpmlint/config
/etc/cupshelpers/preferreddrivers.xml
/etc/pulse/system.pa
/etc/pulse/daemon.conf
/etc/brltty.conf
/etc/numad.conf
...

How would I (in Python 3) get a list of all files (excluding directories) recursively under a specified path? I also want the heading of the paths to mirror the entered path. For example, if I had (while being in /etc) ran find . -type f I would have gotten a list like:

./rsyslog.conf
./request-key.d/cifs.idmap.conf
...

The difference being /etc/... vs ./...

Upvotes: 1

Views: 1362

Answers (2)

mgilson
mgilson

Reputation: 310237

You can os.walk and then look at each of the files checking the "type" with os.path.isfile. That should get you pretty close...

import os
import os.path

for root, dirs, files in os.walk('/path/to/directory'):
    for f in files:
        fname = os.path.join(root, f)
        if os.path.isfile(fname):
            print fname  # or do something else with it...

I'm not sure where you were going with the /etc vs. ./ stuff in your question, but I suspect that if this isn't what you want, then you'll just need to do something like

os.path.relpath(fname, '/path/to/directory')

to get the relative path that you want.

Upvotes: 5

venpa
venpa

Reputation: 4318

You could execute system command in python using subprocess:

import subprocess
output=subprocess.check_output(['find /etc/ -type f'])
print output

or using commands module:

import commands
output=commands.getstatusoutput('find /etc/ -type f')

Upvotes: 0

Related Questions