Finding Java-like file tracing functions in Python

In Java, you can do File.listFiles() and get all the files in a directory. Then you can easily do recursion through the directory trees.

Is there a similar way to do this in Python?

+10
java python
Sep 26 '08 at 17:20
source share
9 answers

Yes there is. The Python path is even better.

There are three possibilities:

1) Like File.listFiles ():

Python has a os.listdir function (path). It works as a Java method.

2) pathname template extension with glob:

The glob module contains functions for listing files on a file system using a Unix shell template, for example.

 files = glob.glob('/usr/joe/*.gif') 

3) Moving a file using walk:

Really nice os.walk Python feature.

The walk method returns a generation function that recursively lists all directories and files below a given starting path.

Example:

 import os from os.path import join for root, dirs, files in os.walk('/usr'): print "Current directory", root print "Sub directories", dirs print "Files", files 
You can even delete directories from "dirs" on the fly so as not to reach this directory: if "joe" is in dirs: dirs.remove ("joe") so as not to go to directories called "joe".

listdir and walk are documented here . glob is documented here .

+25
Sep 26 '08 at 17:30
source share

Like Pythonista for a long time, I have to say that the path / file file manipulation functions in the std library are sub-parameters: they are not object-oriented and reflect the deprecated let-wrap-OS-system functions - a thoughtless philosophy. I would heartily recommend the path module as a wrapper (around os, os.path, glob and tempfile, if you know): much nicer and OOPy: http://pypi.python.org/pypi/path.py/2.2

This is walk () with the path module:

 dir = path(os.environ['HOME']) for f in dir.walk(): if f.isfile() and f.endswith('~'): f.remove() 
+5
Sep 27 '08 at 8:27
source share

Try "listdir ()" in the os ( docs ) module:

 import os print os.listdir('.') 
+3
Sep 26 '08 at 17:26
source share

Directly from the Python referral library

 >>> import glob >>> glob.glob('./[0-9].*') ['./1.gif', './2.txt'] >>> glob.glob('*.gif') ['1.gif', 'card.gif'] >>> glob.glob('?.gif') ['1.gif'] 
+2
Sep 26 '08 at 17:24
source share

Take a look at os.walk() and the examples here . With os.walk() you can easily handle the entire directory tree.

Example from the link above ...

 # Delete everything reachable from the directory named in 'top', # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) 
+2
Sep 26 '08 at 17:27
source share

Use os.path.walk if you want subdirectories as well.

  walk (top, func, arg)

         Directory tree walk with callback function.

         For each directory in the directory tree rooted at top (including top
         itself, but excluding '.'  and '..'), call func (arg, dirname, fnames).
         dirname is the name of the directory, and fnames a list of the names of
         the files and subdirectories in dirname (excluding '.' and '..').  func
         may modify the fnames list in-place (eg via del or slice assignment),
         and walk will only recurse into the subdirectories whose names remain in
         fnames;  this can be used to implement a filter, or to impose a specific
         order of visiting.  No semantics are defined for, or required of, arg,
         beyond that arg is always passed to func.  It can be used, eg, to pass
         a filename pattern, or a mutable object designed to accumulate
         statistics.  Passing None for arg is common.
+2
Sep 26 '08 at 17:31
source share

I would recommend against os.path.walk as it is being removed in Python 3.0. os.walk simpler, anyway, or at least I find it simpler.

+2
Sep 26 '08 at 18:58
source share

You can also check out Unipath , the object-oriented shell of the Python os , os.path and shutil modules.

Example:

 >>> from unipath import Path >>> p = Path('/Users/kermit') >>> p.listdir() Path(u'/Users/kermit/Applications'), Path(u'/Users/kermit/Desktop'), Path(u'/Users/kermit/Documents'), Path(u'/Users/kermit/Downloads'), ... 

Installation through the cheese shop:

 $ pip install unipath 
+1
Aug 27 '13 at 12:50
source share

After seeing what I programmed in python for a long time, I used the os module many times and made my own function to print all the files in a directory.

Code for function:

 import os def PrintFiles(direc): files = os.listdir(direc) for x in range(len(files)): print("File no. "+str(x+1)+": "+files[x]) PrintFiles(direc) 
0
Feb 29 '16 at 17:26
source share



All Articles