473,581 Members | 6,653 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: Using os.walk to return files in subdirectories

dj
Hello All,

I am attempting to us os.walk to populate two lists with values from a
directory. The first list contains all the files in the directory and
subdirectories.
The second list contains only the files in the subdirectories.

Here is the code:

import os

# list of matching files
allfiles = [] #store all files found
subfiles = [] # subdir

for root,dir,files in os.walk("H:/python_experime nts", f1):
# this list has the files in all directories and subdirectories
filelist = [ os.path.join(ro ot,fi) for fi in files if
fi.endswith(".p y") or fi.endswith(".t xt") ]
for f in filelist:
allfiles.append (f)

# split the root
s= root.split(('\\ ') or ('\/'))
print 's ',
print s

# assign the last value to end to come to values in dir
end= s[-1]
print 'end ',
print end
print '\n'

# this list contains only the files in subdirectories
for d in dir:
if end == d:
print 'subdir % s' % (end)
sublist = [ os.path.join(ro ot, fi) for fi in files if
fi.endswith(".p y") or fi.endswith(".t xt")]
for f in sublist:
subfiles.append (f)

for i in subfiles:
print 'subfile', i
for i in allfiles:
print "file ", i

The allfiles list is populated, but the subfiles list is not. Any
Suggetions ?
Jun 27 '08 #1
2 3791
On May 22, 5:24 pm, dj <d.a.aberna...@ gmail.comwrote:
....snip...
for d in dir:
if end == d:
dir is the list of subdirs of the current dir, and the current dir
is NOT a subdir of itself so end == dir is never true

Are you trying to get a list per subdir?

cheers
Jun 27 '08 #2
dj wrote:
Hello All,

I am attempting to us os.walk to populate two lists with values from a
directory. The first list contains all the files in the directory and
subdirectories.
The second list contains only the files in the subdirectories.

Here is the code:

import os

# list of matching files
allfiles = [] #store all files found
subfiles = [] # subdir

for root,dir,files in os.walk("H:/python_experime nts", f1):
# this list has the files in all directories and subdirectories
filelist = [ os.path.join(ro ot,fi) for fi in files if
fi.endswith(".p y") or fi.endswith(".t xt") ]
for f in filelist:
allfiles.append (f)

# split the root
s= root.split(('\\ ') or ('\/'))
print 's ',
print s

# assign the last value to end to come to values in dir
end= s[-1]
print 'end ',
print end
print '\n'

# this list contains only the files in subdirectories
for d in dir:
if end == d:
print 'subdir % s' % (end)
sublist = [ os.path.join(ro ot, fi) for fi in files if
fi.endswith(".p y") or fi.endswith(".t xt")]
for f in sublist:
subfiles.append (f)

for i in subfiles:
print 'subfile', i
for i in allfiles:
print "file ", i

The allfiles list is populated, but the subfiles list is not. Any
Suggetions ?

I think you were trying to make this harder than it actually is. Here is a
tested script that works for me.

import os
basePath = 'c:/Python25'
allfiles = []
subfiles = []

for root, dirs, files in os.walk(basePat h):
for f in files:
if f.endswith('.tx t') or f.endswith('.py '):
allfiles.append (os.path.join(r oot, f))
if root != basePath: # I'm in a subdirectory
subfiles.append (os.path.join(r oot, f))

print "allfiles=" , allfiles
print
print "subfiles=" , subfiles
print
print "len(allfiles)= ", len(allfiles)
print "len(subfiles)= ", len(subfiles)
-Larry Bates
Jun 27 '08 #3

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

Similar topics

5
3329
by: hokiegal99 | last post by:
A few questions about the following code. How would I "wrap" this in a function, and do I need to? Also, how can I make the code smart enough to realize that when a file has 2 or more bad charcters in it, that the code needs to run until all bad characters are gone? For example, if a file has the name "<bad*mac\file" the program has to run...
9
9357
by: hokieghal99 | last post by:
This script is not recursive... in order to make it recursive, I have to call it several times (my kludge... hey, it works). I thought os.walk's sole purpose was to recursively walk a directory structure, no? Also,it generates the below error during the os.renames section, but the odd thing is that it actually renames the files before saying...
6
3338
by: Dreamcatcher | last post by:
Hello, I'm trying to learn some C, reading my book, Beginning Linux Programming I came across the following program. The program is supposed to walk through directory's and print all its subdirectories. However the program never seems to get out of the loop its in. I tried finding the error but I don't see where it goes wrong, hopefully...
7
4535
by: KraftDiner | last post by:
The os.walk function walks the operating systems directory tree. This seems to work, but I don't quite understand the tupple that is returned... Can someone explain please? for root, dirs, files in os.walk('/directory/'): print root # print dirs # print files
8
2279
by: Andre Meyer | last post by:
Hi all os.walk() is a nice generator for performing actions on all files in a directory and subdirectories. However, how can one use os.walk() for walking through two hierarchies at once? I want to synchronise two directories (just backup for now), but cannot see how I can traverse a second one. I do this now with os.listdir() recursively,...
2
4013
by: gregpinero | last post by:
In the example from help(os.walk) it lists this: from os.path import join, getsize for root, dirs, files in walk('python/Lib/email'): print root, "consumes", print sum(), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories
0
212
by: Paul Lemelle | last post by:
Jeff, Thanks for your reply. I would like to like the absolute path of a directory. I thought that os.listdir just returns the nam itself in a data list. I noticed that none was being return in my example. Do you think that I have the arguments misplaced? Thanks, Paul
4
2457
by: Jeff Nyman | last post by:
Greetings all. I did some searching on this but I can't seem to find a specific solution. I have code like this: ========================================= def walker1(arg, dirname, names): DC_List.append((dirname,'')) os.path.walk('\\\\vcdcflx006\\Flex\\Sites', walker1, 0)
6
21062
by: D | last post by:
Hello, How can one exclude a directory (and all its subdirectories) when running os.walk()? Thanks, Doug
0
7783
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8296
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7880
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8157
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6539
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5665
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3794
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2295
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1394
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.