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.

Comments

Grandpa 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!
Tamim Shahriar 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.
Unknown 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)
Vvn 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)
Jerry Steele 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)
Unknown said…
This comment has been removed by the author.
Unknown said…
Sure it's an old posting, but I just wanted to point out the only 2 correct ways of doing file io.
You either do this (preferred):

with open('myfile.txt', 'w') as file:
   #here you do the tree walking

or this longer version (they do exactly the same thing):

try:
   file = open('myfile.txt', 'w')
   #here do the tree walking
finally:
   file.close()

Edit: Removed my first posting, because I forgot to use non-breaking spaces. Fixed it now.
Anonymous said…
Really useful code. It worked beautifully! Thanks.
Worked like a charm.. Excellent...
I am trying to generate an MD5 Hash for a .tar.gz file. It is generating and writing in a text file md5.txt perfectly. Now I want to create a new tar.gz file and adding that 1st tar.gz file + md5.txt file into the new tar file.

The problem is that when I create new tarfile, it copies the old tarfile inside and also adds md5.txt file but the md5.txt file does not have any contains. However, the md5.txt file outside the new tarfile have the hash value.

Does anyone have some idea where I am going wrong or what I am missing. Thanks.

Akash...
draike said…
sir i created a python program using client(mobile) server(PC) bluetooth.its objective is to display the file names of the files of My Documents in mobile. but the problem is that it copies all the files in a directory and not in My document and it copy all the files. i want to view the file names before i copy it. and copy it 1 by 1.
draike said…
sir i created a python program using client(mobile) server(PC) bluetooth.its objective is to display the file names of the files of My Documents in mobile. but the problem is that it copies all the files in a directory and not in My document and it copy all the files. i want to view the file names before i copy it. and copy it 1 by 1.
Paal said…
This program works, but i dont know how to change the default directory.
I've been trying:
os.path.defpath'.:V:\\Kartdata'
and sys.path.append('V:\kartdata')
I want this program to search thru my V:\Kartdata directory. Any leads?

Thanks :)
Paal said…
How do I change the directory tree?
Unknown said…
Hello Experts ,
I am very new to python . i need your great helps

requirement : I need to write python script for list file in a directory and then i need to print the contents of file . can you please help me out!
Thanks in Advance
karthik

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code