472,800 Members | 1,180 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,800 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 4097
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: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.