473,385 Members | 1,769 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

how to get files in a directory


Hi all,

I am trying to find a way to get the files recursively in a given
directory,

The following code is failing, can some one please suggest what could be
problem here
from os import walk,join

for root,dir,files in os.walk("E:\myDir1\MyDir2"):
for i in dir:
for j in files:
fille = root+i+j
print file

Surprisingly if i give os.walk("E:\myDir1") the above code works, but
not if i have 2 levels of directories.

Thanks & Best Regards,
Anand
Jul 18 '05 #1
5 4154
First of all, Jeremy already pointed out that your code has several errors.
I'll assume though that your real code is more complicated and you just
tried to show us a simplification of your code.

On the other hand, without the real code we cannot tell why it works for 1
level and it does not work for 2 levels. As someone pointed out already, it
migh be because you are using "\" instead of "\\" for path separators.
Python will accept "\c" as if it was with double backslashes but it will
reject "\x" because that is a special character.

Based on the example that you gave, you are also misunderstanding os.walk.
os.walk returns 3 values (I'll use the names in your code):
- root - the parent directory at this point in the traversal of the tree
- dir - the list of children directories in root (right below root)
- files - the list of files in root
So the files in the 'files' list are not under dir but under root. So it
does not make sense to loop over 'files' inside the loop over 'dir' or to
join root+i+j. Both your 'i' and your 'j' are just under 'root'.

I'm not sure either what you are trying to do with "root+i+j". You probably
need os.path.join(root,i) and os.path.join(root,j)

Dan

"Anand K Rayudu" <ar*@esi-group.com> wrote in message
news:ma**************************************@pyth on.org...

Hi all,

I am trying to find a way to get the files recursively in a given
directory,

The following code is failing, can some one please suggest what could be
problem here
from os import walk,join

for root,dir,files in os.walk("E:\myDir1\MyDir2"):
for i in dir:
for j in files:
fille = root+i+j
print file

Surprisingly if i give os.walk("E:\myDir1") the above code works, but not
if i have 2 levels of directories.

Thanks & Best Regards,
Anand

Jul 18 '05 #2
Anand K Rayudu wrote:

Hi all,

I am trying to find a way to get the files recursively in a given
directory,

The following code is failing, can some one please suggest what could be
problem here
from os import walk,join

for root,dir,files in os.walk("E:\myDir1\MyDir2"):
for i in dir:
for j in files:
fille = root+i+j
print file

Surprisingly if i give os.walk("E:\myDir1") the above code works, but
not if i have 2 levels of directories.

Thanks & Best Regards,
Anand


Anand,
Does this help?
wes

def GetFilesWithExtRecursively(path,ext_list): #ext_list is like [".h",".cpp",...]
dir_list = []
file_list = []
if not os.path.isdir(path):
print "\a"
return [],[]

filenames = os.listdir( path )

for fn in filenames:
if path[-1] == "/":
xfn = path + fn
else:
xfn = path + "/" + fn
if( os.path.isdir( xfn ) ):
file_list = file_list + GetFilesWithExtRecursively( xfn ,ext_list)
elif( os.path.isfile( xfn ) ):
front,back = os.path.splitext(xfn)
if back in ext_list:
file_list.append( xfn )
return file_list

Jul 18 '05 #3
Anand K Rayudu <ar*@esi-group.com> wrote in message news:<ma**************************************@pyt hon.org>...
Hi all,

I am trying to find a way to get the files recursively in a given
directory,

The following code is failing, can some one please suggest what could be
problem here
from os import walk,join

for root,dir,files in os.walk("E:\myDir1\MyDir2"):
for i in dir:
for j in files:
fille = root+i+j
print file

Surprisingly if i give os.walk("E:\myDir1") the above code works, but
not if i have 2 levels of directories.

Thanks & Best Regards,
Anand

All is wrong!
0. Wrong import
1. not "E:\myDir1\MyDir2", but "E:\\myDir1\\MyDir2"
2. dir and files are in the SAME directory. In other words if the
structure is:
myDir1
MyDir2
somefile.py
the first itteration will give an EMPTY dir= [] and files =
['somefile.py']
Here is an example from the manual:

This example displays the number of bytes taken by non-directory files
in each directory under the starting directory, except that it doesn't
look under any CVS subdirectory

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print root, "consumes",
print sum([getsize(join(root, name)) for name in files]),
print "bytes in", len(files), "non-directory files"
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories

so if you want just print full path of the files in E:\myDir1\MyDir2

for root,dir,files in os.walk("E:\myDir1\MyDir2"):
for j in files:
fille = os.path.join(root,j)
print fille

Do not touch dir. It is supposed to be used to restrict the search.
If you do not modify dir it walk will progress into root's
subdirectories.
Jul 18 '05 #4
Anand K Rayudu <ar*@esi-group.com> wrote in message news:<ma**************************************@pyt hon.org>...
I am trying to find a way to get the files recursively in a given
directory,

The following code is failing, can some one please suggest what could be
problem here
You don't really give enough information, but I'll make some
reasonable guesses. My guess is that you have a directory tree
"E:\myDir1\MyDir2", and that "MyDir2" contains files but no
subdirectories.

for root,dir,files in os.walk("E:\myDir1\MyDir2"):
Here you are iterating over a directory tree. For each directory in
the tree, os.walk returns the path to the directory, a list of the
subdirectories in that directory, and a list of non-directory files in
that directory.
for i in dir:
Here you are examining each of the subdirectories of the current
directory. You are ignoring any files in that directory. So, for the
top-level directory you gave to os.walk, "E:\myDir1\MyDir2", you are
ignoring the actual files in that directory, and examining only its
subdirectories. My guess is that there are no subdirectories, so you
get no results.
Surprisingly if i give os.walk("E:\myDir1") the above code works, but
not if i have 2 levels of directories.


Unsurprisingly. If there are any files in "myDir1", your code would
ignore them, and only find files in its subdirectory, "MyDir2".
Jul 18 '05 #5
Backslash begins an escape sequence in a string literal.
You have a few options:

0. Use a forward slash (which will work in Python for DOS paths):
"E:/myDir1/myDir2""

1. Use the escape sequence for backslash: "E:\\myDir1\\myDir2"

2. Use a raw string: r"E:\myDir1\myDir2"

Further reference:
http://www.python.org/doc/current/ref/strings.html
Surprisingly if i give os.walk("E:\myDir1") the above code works, but
not if i have 2 levels of directories.


Yes, that is kind of surprising. Also, your nested loop...

for i in dir:
for j in files:
fille = root+i+j
print file

.... doesn't make any sense. "dir" is a list of sub-directories in
root, while "files" is a list of non-directory files in root. The
files in "files" are not in the subdirectories.
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Mike | last post by:
I am sure that I am making a simple boneheaded mistake and I would appreciate your help in spotting in. I have just installed apache_2.0.53-win32-x86-no_ssl.exe php-5.0.3-Win32.zip...
4
by: Hal Vaughan | last post by:
I am writing out archive files using ZipOutputStream with the following code: aEntry is a global Array of ZipEntries llData is a LinkedList of the data corresponding to the the ZipEntry of the...
6
by: Peter Row | last post by:
Hi, Can someone give me a set of steps for an ASP.NET project (well actually its just a VB.NET class DLL that implements HttpHandler) that will work when moved to another developers machine? ...
5
by: Bas Hendriks | last post by:
Has anyone any idea how asp.net find it's files back after compiling them to the temporary asp.net directory? I found on numerous webpages that the directorynames are chosen random but cannot find...
10
by: Martin Ho | last post by:
I am running into one really big problem. I wrote a script in vb.net to make a copy of folders and subfolder to another destination: - in 'from.txt' I specify which folders to copy - in...
23
by: **Developer** | last post by:
Is there an easy way to copies all files in a directory into another directory? What about coping subdirectories too? Thanks in advance for any info
18
by: UJ | last post by:
Folks, We provide custom content for our customers. Currently we put the files on our server and people have a program we provide that will download the files. These files are usually SWF, HTML or...
1
by: dkmarni | last post by:
Hi, I am trying to do this perl script, but not able to complete it successfully. Here is the description what the script has to do.. Accept two and only two command line arguments. Again,...
3
by: aRTx | last post by:
I have try a couple of time but does not work for me My files everytime are sortet by NAME. I want to Sort my files by Date-desc. Can anyone help me to do it? The Script <? /* ORIGJINALI
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.