Sunday, May 25, 2008

List of files, directories in Python

Here I present a short python program that prints the list of all files inside the current directory and subdirectories. It prints filename with relative path to the current directory.

import os

for root, dirs, files in os.walk('./'):
for name in files:
filename = os.path.join(root, name)
print filename

You can also print the list of directories only (just print the dirs). Actually I needed this stuff to solve a problem from Google treasure hunt. Let me know if you want me to share the full source code of the solutions of Google treasure hunt. Also share your code, if you have any different idea!

Check the python documentation to learn more about processing Files and Directories.

6 comments:

Steve said...

I am just learning Python and I was wondering a couple of hours ago how one could do this. I think you were reading my mind!

subeen said...

nice to know that :)
let me know if you want to see articles/tips on any topic in my blog. I shall try to write.

geowizard said...

as absolute newby I'm wondering how to write these filenames (and path) to a textfile ... any hints ?
thanks a lot !

sajid said...

just open a file for writing and then write in that file.

import os

f = open('myfile.txt', 'w')

for root, dirs, files in os.walk('./'):
for name in files:
filename = os.path.join(root, name)
s = filename + '\n'
f.write(s)

Viven Rajendra said...

better way to do it:

import os
f = open('myfile.txt', 'w')
for root, dirs, files in os.walk('./'):
  for name in files:
    filename = os.path.abspath(name)
    s = filename + '\n'
f.write(s)

fitzgeraldsteele said...

and really, the best way to concatenate strings in python is to use the join() method (see http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html).

Throw in some list comprehensions for those nested for loops, and now our example looks like:

import os

f = open('myfile.txt', 'w')

# create a list of all files
# using list comprehensions
# should be all on one line
fnames = [os.path.join(root, name)
  for (root,dirs,files) in os.walk('./')
  for name in files]

s = "\n".join(fnames)
f.write(s)