473,769 Members | 8,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

newb question: file searching

I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.

Aug 8 '06
29 2660
Oops, what I wrote above isn't quite correct. As another poster pointed
out, you'd want to do
for file in x[2]:
....

--dave

Aug 8 '06 #11
So far, so good. I just have a few more questions.

Here's my code so far:

import os
top = '/home/USERNAME/'
images = []
for files in os.walk(top, topdown=True):
images += [file for file in files[2] if file.endswith(' jpg')]
print images

I still need to know how I can dynamically get the name of the
directory that my script is in. Also, how can I get it to add the full
path of the file to "images" instead of just the file name. See, when
I go to use a particular image name later on, it won't do me much good
if I don't have the path to it.

Aug 8 '06 #12
ja*******@gmail .com wrote:
hiaips wrote:
ja*******@gmail .com wrote:
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.
dir_name = 'mydirectory'
extension = 'my extension'
import os
files = os.listdir(dir_ name)
files_with_ext = [file for file in files if file.endswith(e xtension)]

That will only do the top level (not subdirectories) , but you can use
the os.walk procedure (or some of the other procedures in the os and
os.path modules) to do that.

--Dave

Thanks, Dave. That's exactly what I was looking for, well, except for
a few small alterations I'll make to achieve the desired effect. I
must ask, in the interest of learning, what is

[file for file in files if file.endswith(e xtension)]

actually doing? I know that 'file' is a type, but what's with the set
up and the brackets and all? Can someone run down the syntax for me on
that? And also, I'm still not sure I know exactly how os.walk() works.
And, finally, the python docs all note that symbols like . and ..
don't work with these commands. How can I grab the directory that my
script is residing in?

Thanks.

'file' *is* the name of the file type, so one shouldn't reuse it as the
name of a variable as Dave did in his example.

the brackets are a "list comprehension" and they work like so:

files_with_ext = []
for filename in files:
if filename.endswi th(extension):
files_with_ext. append(filename )

The above is exactly equivalent to the [filename for filename in
files... ] form.

AFAIK, os.listdir('.') works fine, but you can also use
os.listdir(os.g etcwd()). However, both of those return the current
directory, which can be different than the directory your script's
residing in if you've called os.chdir() or if you start your script
from a different directory.
HTH.

(Also, if you're not already, be aware of os.path.isfile( ) and
os.path.isdir() . They should probably be helpful to you.)

Peace,
~Simon

Aug 8 '06 #13

ja*******@gmail .com wrote:
I must ask, in the interest of learning, what is

[file for file in files if file.endswith(e xtension)]

actually doing? I know that 'file' is a type, but what's with the set
up and the brackets and all?
Other people explained the list comprehension, but you might be
confused about the unfortunate choice of 'file' as the name in this
example. 'file' is a built-in as you remarked. It is allowed, but a bad
idea, to use names that are the same as built-ins. Some people
characterize this as shadowing the built-in.

A similar, common case is when people use the name 'list' for a list
object. They shouldn't.

The example could have been written as:

[f for f in files if f.endswith(exte nsion)]

Aug 8 '06 #14
Okay. This is almost solved. I just need to know how to have each
entry in my final list have the full path, not just the file name.
Also, I've noticed that files are being found within hidden
directories. I'd like to exclude hidden directories from the walk, or
at least not add anything within them. Any advice?

Here's what I've got so far:

def getFileList():
import os
imageList = []
for files in os.walk(os.getc wd(), topdown=True):
imageList += [file for file in files[2] if file.endswith(' jpg') or
file.endswith(' gif')]
return imageList

Aug 8 '06 #15
At Tuesday 8/8/2006 17:55, ja*******@gmail .com wrote:
>I must ask, in the interest of learning, what is

[file for file in files if file.endswith(e xtension)]

actually doing? I know that 'file' is a type, but what's with the set
up and the brackets and all? Can someone run down the syntax for me on
that?
Note: "file" is really a bad name here; rebinding builtins is never a
good idea. But unfortunately names like "file", "dir", "dict" are
very handy when you need a dummy variable like this, so people tend
to use them.
This has exactly the same meaning:

[x for x in files if x.endswith(exte nsion)]

>I still need to know how I can dynamically get the name of the
directory that my script is in.
os.path.dirname (os.path.abspat h(sys.modules[__name__].__file__))
>Also, how can I get it to add the full
path of the file to "images" instead of just the file name. See, when
I go to use a particular image name later on, it won't do me much good
if I don't have the path to it.
Look at os.path.join()

Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 8 '06 #16
ja*******@gmail .com wrote:
And, finally, the python docs all note that symbols like . and ..
don't work with these commands.
Where did you read that? The docs for os.listdir do say that '.' and
'..' are (sensibly) not returned as *results*. AFAIK there is nothing
to stop you using '.' or '..' as a path *argument* where
appropriate/useful.
How can I grab the directory that my
script is residing in?
C:\junk>type scriptdir.py
import sys, os.path
scriptpath = sys.argv[0] # read the docs for sys.argv
print "script is", scriptpath
scriptdir = os.path.split(s criptpath)[0] # read the docs for
os.path.split
print "script lives in", scriptdir
C:\junk>scriptd ir.py
script is C:\junk\scriptd ir.py
script lives in C:\junk

C:\junk>move scriptdir.py \bin

C:\junk>scriptd ir.py
script is c:\bin\scriptdi r.py
script lives in c:\bin

[Curiosity: drive letter is upper-case in first example, lower in
second]

HTH,
John

Aug 8 '06 #17
ja*******@gmail .com wrote:
Okay. This is almost solved. I just need to know how to have each
entry in my final list have the full path, not just the file name.
from http://docs.python.org/lib/os-file-dir.html:

walk() generates the file names in a directory tree, by walking the
tree either top down or bottom up. For each directory in the tree
rooted at directory top (including top itself), it 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 contain 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).

--------

So walk yields a 3-tuple, not just a filename. You seem to be somewhat
aware of this where you refer to files[2] in your list comprehension,
but I believe that is not constructed correctly.

Try this (untested):

def get_image_filep aths(target_fol der):
"""Return a list of filepaths (path plus filename) for all images
in target_folder or any subfolder"""
import os
images = []
for dirpath, dirnames, filenames in os.walk(target_ folder):
for filename in filenames:
normalized_file name = filename.lower( )
if normalized_file name.endswith(' .jpg') or
normalized_file name.endswith(' .gif'):
filepath = os.path.join(di rpath, filename)
images.append(f ilepath)
return images

import os
images = get_image_filep aths(os.getcwd( ))
Also, I've noticed that files are being found within hidden
directories. I'd like to exclude hidden directories from the walk, or
at least not add anything within them. Any advice?
Decide how you identify a hidden directory and test dirpath before
adding it to the images list. E.g., test whether dirpath starts with
'.' and skip it if so.
>
Here's what I've got so far:

def getFileList():
import os
imageList = []
for files in os.walk(os.getc wd(), topdown=True):
imageList += [file for file in files[2] if file.endswith(' jpg') or
file.endswith(' gif')]
return imageList
Aug 8 '06 #18
Also, I've noticed that files are being found within hidden
directories. I'd like to exclude hidden directories from the walk, or
at least not add anything within them. Any advice?
The second item in the tuple yielded by os.walk() is a list of
subdirectories inside the directory indicated by the first item in the
tuple. You can remove values from this list at runtime to have os.walk
skip over them.

Aug 8 '06 #19
ja*******@gmail .com wrote:
[...]
that? And also, I'm still not sure I know exactly how os.walk() works.
And, finally, the python docs all note that symbols like . and ..
don't work with these commands. How can I grab the directory that my
script is residing in?
os.getcwd() will get you the directory your script is in (at least as
long as you're running the script from the current directory :-)

Here's my version of how to it (comments below):

def collect_ext(*ex tensions):
"""Return a list of files from current directory and downwards
that have given extensions. Call it like collect_ext('.p y',
'.pyw')
"""
res = []
for dirname, _, files in os.walk(os.getc wd()):
for fname in files:
name, ext = os.path.splitex t(fname)
if ext in extensions:
res.append(os.p ath.join(dirnam e, fname))
return res

Each time around the outer for-loop, os.walk() gives us all the
filenames (as a list into the files variable) in a sub-directory. We
need to run through this list (inner for-loop), and save all files with
one of the right extensions. (os.walk() also gives us a list of all
subdirectories, but since we don't need it, I map it to the _ (single
underscore) variable which is convention for "I'm not using this
part").

note1: notice the "*" in the def line, it makes the function accept a
variable number of arguments, so you can call it as collect_ext('.p y')
but also as collect_ext('.p y', '.pyw', '.pyo'). Inside the function,
what you've called it with is a list (or a tuple, I forget), which
means I can use the _in_ operator in the if test.

note2: I use os.path.join() to attach the directory name to the
filename before appending it to the result. It seems that might be
useful ;-)

hth,
-- bjorn

Aug 8 '06 #20

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

Similar topics

0
2132
by: claudel | last post by:
Hi I have a newb PHP/Javascript question regarding checkbox processing I'm not sure which area it falls into so I crossposted to comp.lang.php and comp.lang.javascript. I'm trying to construct a checkbox array in a survey form where one of the choices is "No Preference" which is checked by default. If the victim chooses other than "No Preference", I'd like to uncheck
5
2035
by: Alexandre | last post by:
Hi, Im a newb to dev and python... my first sefl assigned mission was to read a pickled file containing a list with DB like data and convert this to MySQL... So i wrote my first module which reads this pickled file and writes an XML file with list of tables and fields (... next step will the module who creates the tables according to details found in the XML file). If anyone has some minutes to spare, suggestions and comments would be...
24
2375
by: Apotheosis | last post by:
The problem professor gave us is: Write a program which reads two integer values. If the first is less than the second, print the message "up". If the second is less than the first, print the message "down" If the numbers are equal, print the message "equal" If there is an error reading the data, print a message containing the word "Error" and perform exit( 0 ); And this is what I wrote:
5
1911
by: none | last post by:
hi all, (i am running on win 2k pro). i saw a program i like on a website and when i went to download it it was just a load of 'c' code. now, i know very little about 'c' or programming but I downloaded 'miracle c' and pasted the code in and when i comiled it i got a load of errors. (below)
11
1999
by: The_Kingpin | last post by:
Hi all, I'm new to C programming and looking for some help. I have a homework project to do and could use every tips, advises, code sample and references I can get. Here's what I need to do. I have a file named books.txt that contains all the informations on the books. Each book is a struc containing 6 fields written on separated line in the
2
1198
by: JR | last post by:
I have tried searching boards but have not been able to find an answer. What is the best way to display text from a log.txt file and then display it in three seperate text boxes? I have a log file that is continually going to have 3 temperatures appended to it. I need to read that temperature in from the log file and display it to the user. The temperatures are seperated by commas. I was reading and is Streamreader
1
1000
by: jgibbens | last post by:
First, thank you for even looking at my question. I am using VB 2005 and I have a question about XML. what I want to do is: 1. keep adding to this file with out over writing it 2. be able to change stuff the XML without overwriting the rest of the file This is the XML I have:
0
9589
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
9423
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
10049
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
9998
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,...
0
9865
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7413
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3967
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
3
2815
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.