473,573 Members | 5,052 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dumb glob question

I've run into an issue with glob and matching filenames with brackets '[]'
in them. The problem comes when I'm using part of such a filename as the
path I'm passing to glob. Here's a trimmed down dumb example. Let's say I
have a directory with the following files in it.

foo.par2
foo.vol0+1.par2
foo.vol1+1.par2
zzz [foo].par2
zzz [foo].vol0+1.par2
zzz [foo].vol1+1.par2

While processing one of the files I want to do certain things in batch so
I've been using glob as a means to get all of the files in a set. The
following code will print the filenames for parity volumes in each set
while working with the base checksum, unless there are brackets in the
name.
#re2 = re.compile(r'vo l', re.IGNORECASE)

#for nuke in glob.glob('*.pa r2'):
# if not re2.search(nuke ):
# list = glob.glob(nuke[:-5]+'*vol*')
# for name in list: print os.path.join(os .getcwd(),name)

I'm sure there is something obvious I'm missing. I figured I could use
something like re.escape on the trimmed filename for matching but that
hasn't worked either. Using win32api.FindFi les instead of glob works but
I'd obviously rather do it the _right_ way and have it work properly in
*nix too.
Jul 18 '05 #1
4 3429
code like below willprint all files ending on 'par2', except tose not
containong 'vol' from the 5th position. is that what you need?
-import glob
-for nuke in glob.glob(r"""c :\temp\*.par2"" "):
- try:
- nuke.index('vol ', 5)
- print nuke
- except ValueError, e:
- print e

Jul 18 '05 #2
"wi******@hotma il.com" <wi******@hotma il.com> wrote in comp.lang.pytho n:
code like below willprint all files ending on 'par2', except tose not
containong 'vol' from the 5th position. is that what you need?
-import glob
-for nuke in glob.glob(r"""c :\temp\*.par2"" "):
- try:
- nuke.index('vol ', 5)
- print nuke
- except ValueError, e:
- print e


Not quite. I'm sorry my example wasn't very clear. While working with any
single file I need to be able to build a list of all the other files in a
particular set. Basically I just need globbing of the base filename.

glob.glob(basen ame+'.*some_ext ension')

So if I was working with 'foo.par2' at the moment...

glob.glob(filen ame[:-5]+'.*par2')

would catch all of the files belonging to the set including 'foo.par2'
'foo.vol0+1.par 2' 'foo.vol1+1.par 2' etc.

This works great (as expected) until you are working with a filename with
brackets '[]' in it. Then glob just returns an empty list. So if I happen
to be processing 'foo [bar].par2'

glob.glob(filen ame[:-5]+'.*par2')

doesn't return anything. Using win32api.FindFi les(filename[:-5]+'.*par2')
works perfectly, but I don't want to rely on win32api functions. I hope
that made more sense :).

Jul 18 '05 #3
Python Dunce wrote:
So if I happen
to be processing 'foo [bar].par2'

glob.glob(filen ame[:-5]+'.*par2')

doesn't return anything. Using win32api.FindFi les(filename[:-5]+'.*par2')
works perfectly, but I don't want to rely on win32api functions. I hope
that made more sense :).


If you look in the source for glob.py, you will find that it calls the
fnmatch module, and this is the docstring for fnmatch.transla te():

"""Translat e a shell PATTERN to a regular expression.

There is no way to quote meta-characters.
"""

So you cannot do what you want with glob.

You can replace [] with ? in your glob string, if you are sure that
there won't be other characters there. That's a bit of a hack, and I
wouldn't do it.

In my mind it would probably be best to do:

re_vol = re.compile(re.e scape(startpart ) + ".*vol.*")
lst = [filename for filename in os.listdir(".") if re_vol.match(fi lename)]

I changed "list" to "lst" because the former shadows a built-in.
--
Michael Hoffman
Jul 18 '05 #4
Michael Hoffman <ca*******@mh39 1.invalid> wrote in comp.lang.pytho n:
Python Dunce wrote:
So if I happen
to be processing 'foo [bar].par2'

glob.glob(filen ame[:-5]+'.*par2')

doesn't return anything. Using
win32api.FindFi les(filename[:-5]+'.*par2') works perfectly, but I don't
want to rely on win32api functions. I hope that made more sense :).


If you look in the source for glob.py, you will find that it calls the
fnmatch module, and this is the docstring for fnmatch.transla te():

"""Translat e a shell PATTERN to a regular expression.

There is no way to quote meta-characters.
"""

So you cannot do what you want with glob.

You can replace [] with ? in your glob string, if you are sure that
there won't be other characters there. That's a bit of a hack, and I
wouldn't do it.

In my mind it would probably be best to do:

re_vol = re.compile(re.e scape(startpart ) + ".*vol.*")
lst = [filename for filename in os.listdir(".") if
re_vol.match(fi lename)]

I changed "list" to "lst" because the former shadows a built-in.


Thanks, that should do the trick! I had tried basically the same thing
once but I was getting back empty lists. I think it was just a brain fart
involving a case sensitive regex that didn't match the files I was testing
it on :/.
Jul 18 '05 #5

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

Similar topics

15
3072
by: Georgy Pruss | last post by:
On Windows XP glob.glob doesn't work properly for files without extensions. E.g. C:\Temp contains 4 files: 2 with extensions, 2 without. C:\Temp>dir /b * aaaaa.aaa bbbbb.bbb ccccc ddddd C:\Temp>dir /b *.
5
2322
by: Elbert Lev | last post by:
#Here is the script #Python 2.3 on W2K import glob name = glob.glob(u"./*.mp3") print type(name) name = glob.glob(u"*.mp3") print type(name)
2
5012
by: Zain Homer | last post by:
Someone please let me know if I'm sending this to the wrong email alias... I'm wondering why we can't use the glob module to glob with curly brackets like we can from the command line (at least in tcsh). Is there a shell standard for which the python glob module has been designed which prevents the implimentation of the {}'s? For...
6
3285
by: Hitesh | last post by:
import string import os f = open ("c:\\servername.txt", 'r') linelist = f.read() lineLog = string.split(linelist, '\n') lineLog = lineLog #print lineLog for l in lineLog:
2
1386
by: J | last post by:
Greetings Group- I'm trying to put together a pattern matching script that scans a directory tree for tif images contained in similar folder names, but running into a NewB problem already. Is it the way I'm trying to join multiple paths? Any help would be greatly appericated. Thanks, J! import glob, sys, os topdir = sys.argv
8
2364
by: mark.bergman | last post by:
I am porting from Digital Unix to Linux (RHEL 4), and am seeing a difference in the return value of glob(). Given a non-existant directory "/tmp/a", and the following line of code: result = glob("/tmp/a", GLOB_ERR, NULL, &globInfo); - result is set to GLOB_NOMATCH on both platforms. However, if the first parameter is changed to "/tmp/a/*",...
3
1905
by: billiejoex | last post by:
os.listdir(path) return a list of file names independently if the path- argument used is absolute or relative: '/home/user' glob.glob, instead, return file names only if given path is relative: '/home/user/Desktop
1
1829
by: crybaby | last post by:
when I do this in my python code and run it in windows xp, it creates ctemp/..../.../.../../ so on and creates file t. Not file starting with the name complist and ending with .txt (complist*.txt). Any idea why this may be? glob only works in *nix not on windows? os.renames(glob.glob('complist*.txt')...
5
2402
by: jo3c | last post by:
hi everyone happy new year! im a newbie to python i have a question by using linecache and glob how do i read a specific line from a file in a batch and then insert it into database? because it doesn't work! i can't use glob wildcard with linecache
0
7707
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
8037
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. ...
0
8215
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...
0
8086
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
6432
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
5605
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
5296
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...
0
3737
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
1325
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.