473,725 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exclude Directories from os.walk

D
Hello,

How can one exclude a directory (and all its subdirectories) when
running os.walk()?

Thanks,

Doug
Oct 21 '08 #1
6 21106
D wrote:
Hello,

How can one exclude a directory (and all its subdirectories) when
running os.walk()?

Thanks,

Doug
for base, dirs, files in os.walk('wherev er'):
if 'RCS' in dirs:
dirs.remove('RC S')

As described in the os.walk docs.
--Scott David Daniels
Sc***********@A cm.Org
Oct 21 '08 #2
D wrote:
Hello,

How can one exclude a directory (and all its subdirectories) when
running os.walk()?
Just remove it from the dirnames yielded:

<code>
import os

for dirpath, dirnames, filenames in os.walk ("c:/temp"):
print dirpath
if "archive" in dirnames:
dirnames.remove ("archive")

</code>

TJG
Oct 21 '08 #3
D
Ok, my brain's apparently not working right today.. what I'd like to
do is allow the user to specify a directory to exclude (ex- "C:\temp
\test") - then, when os.walk gets to "C:\temp\te st", it excludes that
directory and all its subdirectories (so, "C:\temp\mytest \test" should
still be recursed). Isn't what's posted above keying just upon the
final subdirectory (i.e. "test") instead of the full path as a whole?

Oct 21 '08 #4
You then have to also check the base:

for d in dirs[:]:
if os.path.join(ba se, d) == EXCLUDED_DIR
dirs.remove(d)

or

if base == EXCLUDED_DIR
while dirs: dirs.pop()
continue

WARNING: untest code
- Show quoted text -

On Tue, Oct 21, 2008 at 6:13 PM, D <dm*******@gmai l.comwrote:
Ok, my brain's apparently not working right today.. what I'd like to
do is allow the user to specify a directory to exclude (ex- "C:\temp
\test") - then, when os.walk gets to "C:\temp\te st", it excludes that
directory and all its subdirectories (so, "C:\temp\mytest \test" should
still be recursed). Isn't what's posted above keying just upon the
final subdirectory (i.e. "test") instead of the full path as a whole?

--
http://mail.python.org/mailman/listinfo/python-list


--
or*****@orestis .gr
http://orestis.gr
Oct 21 '08 #5
D
On Oct 21, 1:46*pm, "Orestis Markou" <ores...@oresti s.grwrote:
You then have to also check the base:

for d in dirs[:]:
*if os.path.join(ba se, d) == EXCLUDED_DIR
* *dirs.remove(d)

or

if base == EXCLUDED_DIR
* while dirs: dirs.pop()
continue

WARNING: untest code
- Show quoted text -

On Tue, Oct 21, 2008 at 6:13 PM, D <dmcclo...@gmai l.comwrote:
Ok, my brain's apparently not working right today.. what I'd like to
do is allow the user to specify a directory to exclude (ex- "C:\temp
\test") - then, when os.walk gets to "C:\temp\te st", it excludes that
directory and all its subdirectories (so, "C:\temp\mytest \test" should
still be recursed). *Isn't what's posted above keying just upon the
final subdirectory (i.e. "test") instead of the full path as a whole?
--
http://mail.python.org/mailman/listinfo/python-list

--
ores...@orestis .grhttp://orestis.gr
Works like a charm - thanks to everyone for your help!

Doug
Oct 21 '08 #6
D wrote:
Ok, my brain's apparently not working right today.. what I'd like to
do is allow the user to specify a directory to exclude (ex- "C:\temp
\test") - then, when os.walk gets to "C:\temp\te st", it excludes that
directory and all its subdirectories (so, "C:\temp\mytest \test" should
still be recursed). Isn't what's posted above keying just upon the
final subdirectory (i.e. "test") instead of the full path as a whole?
def canonical(path_ name):
return os.path.normpat h(os.path.abspa th(path_name))

forbidden = 'a/b/c'
home, final = os.path.split(c anonical(forbid den))
for base, dirs, files in os.walk('wherev er'):
if final in dirs and home == canonical(base) :
dirs.remove(fin al)
--Scott David Daniels
Sc***********@A cm.Org
Oct 21 '08 #7

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

Similar topics

1
582
by: Laura McCord | last post by:
Hi, I need to delete all directories in /var/www/html/test that are older than five days. I am new to python so how would I get started? Any tips or suggestions would be appreciated. Thanks, Laura
3
1675
by: Haim Ashkenazi | last post by:
Hi I have to write a function that returns a list of all directories under <PATH> (should work on linux and windows). it should be easy to write a loop that goes through every directory... and so on, but I was wondering if there's faster/more economic way, something like 'find <PATH> -type d'. I couldn't find any 'find' module for python. any ideas?
11
3221
by: rbt | last post by:
Is there an easy way to exclude binary files (I'm working on Windows XP) from the file list returned by os.walk()? Also, when reading files and you're unsure as to whether or not they are ascii or binary, I've always thought it safer to 'rb' on the read, is this correct... and if so, what's the reasoning behind this? Again all of this pertains to files on Windows XP and Python 2.4 Many thanks!
5
655
by: rbt | last post by:
What is the most efficient way to recursively remove files and directories? Currently, I'm using os.walk() to unlink any files present, then I call os.walk() again with the topdown=False option and get rid of diretories with rmdir. This works well, but it seems that there should be a more efficient way. Here are my function definitions: def remove_files(target_dir): # This attempts to remove _all_ files from a directory. # Use with...
5
3293
by: KraftDiner | last post by:
Hi I need help writing a python script that traverses (recursivly) a directory and its sub directories and processes all files in the directory. So at each directory if there are files in it I must build a list of those files and process them by exectuing a system command (exec?) Can some one tell me what methods to use to: a) Walk the directory tree b) execute a system command with parameters.
5
2915
by: Jandre | last post by:
Hi I am a python novice and I am trying to write a python script (most of the code is borrowed) to Zip a directory containing some other directories and files. The script zips all the files fine but when it tries to zip one of the directories it fails with the following error: "IOError: Permission denied: 'c:\\aaa\\temp'" The script I am using is:
9
2873
by: silverburgh.meryl | last post by:
i am trying to use python to walk thru each subdirectory from a top directory. Here is my script: savedPagesDirectory = "/home/meryl/saved_pages/data" dir=open(savedPagesDirectory, 'r') for file in dir: if (isdir(file)): # get the full path of the file
3
1955
by: misceverything | last post by:
I am writing a script that will backup specified folders from one hard drive to another (for example, backup source "C:\DATA", destination "D: \Backup"), and was thinking of using shutil. What I would like to do is recursively backup the specified directories (which copytree will do), but be able to specify exclusion directories (which copytree does not appear to allow you to do). My initial thoughts were I'll probably have to use...
4
2466
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)
0
8889
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8099
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.