473,594 Members | 2,651 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Perl file::find module equivalent in Python?

Hi. Does anyone know if there's an equivalent of Perl's file::find
module in Python? It traverses a directory. I've googled extensively and
checked this newsgroup and can't find anything like it for Python.

I'd be using it in Linux to regularly search for files with a script. Is
this a good application for Python or does Perl have more functionality
for quick & simple scripting in Linux?

Thanks.

-Greg Yasko

Jul 18 '05 #1
3 6997

Greg> Hi. Does anyone know if there's an equivalent of Perl's file::find
Greg> module in Python? It traverses a directory. I've googled
Greg> extensively and checked this newsgroup and can't find anything
Greg> like it for Python.

I've never used file::find, but from your short description ("traverses a
directory"), I suspect you're looking for os.listdir, os.path.walk or
perhaps glob.glob:

listdir(...)
listdir(path) -> list_of_strings

Return a list containing the names of the entries in the directory.

path: path of directory to list

The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the directory.

walk(top, func, arg)
Directory tree walk with callback function.

For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
dirname is the name of the directory, and fnames a list of the names of
the files and subdirectories in dirname (excluding '.' and '..'). func
may modify the fnames list in-place (e.g. via del or slice assignment),
and walk will only recurse into the subdirectories whose names remain in
fnames; this can be used to implement a filter, or to impose a specific
order of visiting. No semantics are defined for, or required of, arg,
beyond that arg is always passed to func. It can be used, e.g., to pass
a filename pattern, or a mutable object designed to accumulate
statistics. Passing None for arg is common.

glob(pathname)
Return a list of paths matching a pathname pattern.

The pattern may contain simple shell-style wildcards a la fnmatch.

Skip

Jul 18 '05 #2
Skip Montanaro wrote:
Greg> Hi. Does anyone know if there's an equivalent of Perl's file::find
Greg> module in Python? It traverses a directory. I've googled
Greg> extensively and checked this newsgroup and can't find anything
Greg> like it for Python.

I've never used file::find, but from your short description ("traverses a
directory"), I suspect you're looking for os.listdir, os.path.walk or
perhaps glob.glob:

Skip

Thanks for answering my question. I knew there had to be some way to do
it:-)

Jul 18 '05 #3
Skip:
I've never used file::find, but from your short description ("traverses a
directory"), I suspect you're looking for os.listdir, os.path.walk or
perhaps glob.glob:


There's also in 2.3 os.walk

Help on function walk in module os:

walk(top, topdown=True, onerror=None)
Directory tree generator.

For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple

dirpath, dirnames, filenames

dirpath is a string, the path to the directory. dirnames is a list of
the names of the subdirectories in dirpath (excluding '.' and '..').
filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists are just names, with no path
components.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(di rpath, name).

If optional arg 'topdown' is true or not specified, the triple for a
directory is generated before the triples for any of its subdirectories
(directories are generated top down). If topdown is false, the triple
for a directory is generated after the triples for all of its
subdirectories (directories are generated bottom up).

When topdown is true, the caller can modify the dirnames list in-place
(e.g., via del or slice assignment), and walk will only recurse into the
subdirectories whose names remain in dirnames; this can be used to prune
the search, or to impose a specific order of visiting. Modifying
dirnames when topdown is false is ineffective, since the directories in
dirnames have already been generated by the time dirnames itself is
generated.

By default errors from the os.listdir() call are ignored. If
optional arg 'onerror' is specified, it should be a function; it
will be called with one argument, an os.error instance. It can
report the error to continue with the walk, or raise the exception
to abort the walk. Note that the filename is available as the
filename attribute of the exception object.

Caution: if you pass a relative pathname for top, don't change the
current working directory between resumptions of walk. walk never
changes the current directory, and assumes that the client doesn't
either.

Example:

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

Andrew
da***@dalkescie ntific.com
Jul 18 '05 #4

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

Similar topics

5
1584
by: Xah Lee | last post by:
© # this is an example of for statement © # the % symbol calculates the remainder © # of division. © # the range(m,n) function © # gives a list from m to n-1. © © a = range(1,51) © for x in a: © if x % 2 == 0: © print x, 'even'
4
3050
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be
44
4024
by: Xah Lee | last post by:
here's a large exercise that uses what we built before. suppose you have tens of thousands of files in various directories. Some of these files are identical, but you don't know which ones are identical with which. Write a program that prints out which file are redundant copies. Here's the spec. -------------------------- The program is to be used on the command line. Its arguments are one or
5
2164
by: Mothra | last post by:
Hi All, I am the current author of the Astro-Sunrise perl module http://search.cpan.org/~rkhill/Astro-Sunrise-0.91/Sunrise.pm and was wondering if it would be worth while to convert it to python. First off, I have never programmed in python. I would like to use this project to learn python. I was wondering if there was a "How to program python for perl programmers" Kinda like what is different between the two, pitfalls for perl...
1
3619
by: smsabu2002 | last post by:
Hi, I am facing the build problem while installing the DBD-MySql perl module (ver 2.9008) using both GCC and CC compilers in HP-UX machine. For the Build using GCC, the compiler error is produced due to the unknown GCC compiler option "+DAportable". For the Build using CC, the preprocessor error is produced due to the recursive declration of macro "PerlIO" in perlio.h file.
0
2382
by: Envex Developments | last post by:
Hey guys, I have a need to install the DBD::Pg Perl module on many shared web servers, which do not have PostgreSQL installed. Then the DBD::Pg module will just connect to a remote PostgreSQL database, hosted elsewhere. I'm having some problems doing this. First off, I modified the Makefile.PL, and added the three following links just above the check for environment variables:
0
2293
by: Envex Developments | last post by:
Hey guys, I have a need to install the DBD::Pg Perl module on many shared web servers, which do not have PostgreSQL installed. Then the DBD::Pg module will just connect to a remote PostgreSQL database, hosted elsewhere. I'm having some problems doing this. First off, I modified the Makefile.PL, and added the three following links just above the check for environment variables:
6
5399
by: Keith Lee | last post by:
All: I am attempting to compile the perl module Device::SerialPort and get this error during make -- Manifying blib/man3/Device::SerialPort.3pm Can't open blib/man3/Device::SerialPort.3pm for writing: Invalid argument at /usr/lib/perl5/5.8.8/ExtUtils/Command/MM.pm line 132 make: *** Error 22 $ make all Manifying blib/man3/Device::SerialPort.3pm Can't open blib/man3/Device::SerialPort.3pm for writing: Invalid argument
2
3797
by: sbettadpur | last post by:
hello, I am trying to install the Text::NLP::Stanford::EntityExtract perl module on windows xp. But its not installing properly... can anybody tell solution for the above problem. But its installing successfully on Linux machine. The following error i was getting while installing.......
0
7941
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
7874
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8368
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...
1
8000
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
5738
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
5404
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
3895
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2383
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
1476
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.