473,785 Members | 2,641 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about listdir/regex/sort

2 New Member
Hi all. I'm kind of a python noobie, this is for my first usefull program, beyond just playing around with the language. Any help is appreciated. Here's the code that throws an error.

Expand|Select|Wrap|Line Numbers
  1. import re, os
  2.  
  3. files = os.listdir(os.getcwd())
  4. #files = ['blue13', 'red011', 'yellow1', 'green1000']
  5.  
  6. def getnum(filename): return float(re.findall(r'\d+',filename)[0])
  7. def numsort(a,b): return cmp(getnum(a),getnum(b))
  8.  
  9. files.sort(numsort)
  10. print files
this throws me
Expand|Select|Wrap|Line Numbers
  1. IndexError: list index out of range
if I switch the "files = " line for the commented one, everything works as it should

I've been banging my head on the keyboard for a couple hours now. It may be simple but I just don't see what's wrong.

Anyway... thanks for the help.
Jun 14 '07 #1
4 3703
bvdet
2,851 Recognized Expert Moderator Specialist
Hi all. I'm kind of a python noobie, this is for my first usefull program, beyond just playing around with the language. Any help is appreciated. Here's the code that throws an error.

Expand|Select|Wrap|Line Numbers
  1. import re, os
  2.  
  3. files = os.listdir(os.getcwd())
  4. #files = ['blue13', 'red011', 'yellow1', 'green1000']
  5.  
  6. def getnum(filename): return float(re.findall(r'\d+',filename)[0])
  7. def numsort(a,b): return cmp(getnum(a),getnum(b))
  8.  
  9. files.sort(numsort)
  10. print files
this throws me
Expand|Select|Wrap|Line Numbers
  1. IndexError: list index out of range
if I switch the "files = " line for the commented one, everything works as it should

I've been banging my head on the keyboard for a couple hours now. It may be simple but I just don't see what's wrong.

Anyway... thanks for the help.
You are encountering files that have no numbers in them. Example:
Expand|Select|Wrap|Line Numbers
  1. >>> getnum('split300.py')
  2. 300.0
  3. >>> getnum('xmlscanner.py')
  4. Traceback (most recent call last):
  5.   File "<interactive input>", line 1, in ?
  6.   File "C:\SDS2_7.0\macro\Work In Progress\re_files_with_numbers.py", line 7, in getnum
  7.     return float(re.findall(r'\d+',filename)[0])
  8. IndexError: list index out of range
  9. >>> 
Jun 14 '07 #2
bartonc
6,596 Recognized Expert Expert
Hi all. I'm kind of a python noobie, this is for my first usefull program, beyond just playing around with the language. Any help is appreciated. Here's the code that throws an error.

Expand|Select|Wrap|Line Numbers
  1. import re, os
  2.  
  3. files = os.listdir(os.getcwd())
  4. #files = ['blue13', 'red011', 'yellow1', 'green1000']
  5.  
  6. def getnum(filename): return float(re.findall(r'\d+',filename)[0])
  7. def numsort(a,b): return cmp(getnum(a),getnum(b))
  8.  
  9. files.sort(numsort)
  10. print files
this throws me
Expand|Select|Wrap|Line Numbers
  1. IndexError: list index out of range
if I switch the "files = " line for the commented one, everything works as it should

I've been banging my head on the keyboard for a couple hours now. It may be simple but I just don't see what's wrong.

Anyway... thanks for the help.
And, just as a tip: Python allows the style of function def that you have use, but please don't do it. You will like yourself, and your program much better in the long run (because you will be able to read it more easily) if you stick with indents:
Expand|Select|Wrap|Line Numbers
  1. import re, os
  2.  
  3. files = os.listdir(os.getcwd())
  4. #files = ['blue13', 'red011', 'yellow1', 'green1000']
  5.  
  6. def getnum(filename):
  7.     return float(re.findall(r'\d+',filename)[0])
  8. def numsort(a,b):
  9.     return cmp(getnum(a),getnum(b))
  10.  
  11. files.sort(numsort)
  12. print files
For example, at first glance I couldn't see these functions.
Jun 14 '07 #3
bvdet
2,851 Recognized Expert Moderator Specialist
Try this:
Expand|Select|Wrap|Line Numbers
  1. def getnum(filename):
  2.     m = re.search(r'\d+',filename)
  3.     if m: return int(m.group(0))
  4.     return None
Jun 14 '07 #4
quailman
2 New Member
Wow! thanks you guys for the quick response. That took care of it, it's up and running like it should.

Just for reference, here's what it looks like now.

Expand|Select|Wrap|Line Numbers
  1. import re,os
  2.  
  3. files = os.listdir(os.getcwd())
  4. #files = ['blue13', 'red011', 'yellow', 'green1000']
  5.  
  6. def numsort(c,d):
  7.         def getnum(filename):
  8.                 m = re.search(r'\d+',filename)
  9.                 if m: return float(m.group(0))
  10.                 return None
  11.         return cmp(getnum(c),getnum(d))
  12.  
  13. files.sort(numsort)
  14. print files
Thanks again! I'll likely be back!
Jun 14 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

11
23037
by: Jason Kratz | last post by:
OK. I've search on google groups and around the web for this and I haven't found an answer. I'm a Python newbie and have what I assume is a basic question. os.listdir takes a pathname as an arg but it doesn't actually list the contents of the dir I pass in. it always operates on the current dir (wherever the script is run) and I have to chdir beforehand. Is that how its supposed to work? If so what is the point in passing in a...
8
2450
by: Hannu Kankaanp?? | last post by:
This may be a bug or simply a strange result of undefined behaviour, but this is what I get with Python 2.3.2 on Windows XP: >>> import os >>> os.listdir('') >>> os.listdir(u'')
14
1895
by: Reinhold Birkenfeld | last post by:
Hello, I recently ported a simple utility script to analyze a data file from Perl to Python that uses regex substitutions, not more complex than re1 = re.compile(r"\s*<.*>\s*") re2 = re.compile(r".*\((.*)\).*") re3 = re.compile(r'^"(.*)"$') When run without these regex substitutions, the scripts' speed is nearly
4
3439
by: Python Dunce | last post by:
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 .par2 zzz .vol0+1.par2
15
2581
by: Riccardo Galli | last post by:
Hi, I noticed that when I use os.listdir I need to work with absolute paths 90% of times. While I can use a for cycle, I'd prefere to use a list comprehension, but it becomes too long. I propose to add an 'abs' keyword which would make os.listdir return the absolute path of files instead of a relative path. This would bring only advantages, I think.
2
1360
by: bebop | last post by:
Hi, I have a Regular Expression that will match the format a user provides in a textbox. Ex. User types Brown,Joe in the textbox I would like the expression to have both whitespace and non-whitespace options after the comma.
1
3270
by: kai | last post by:
Hello, I use dircache.listdir(myDir) in my module repeatedly. On OS WIN 2000 listdir() will re-read the directory structure! But on AIX, listdir() will not re-read the directory structure (see Python Library Reference). I work with python version 2.2. Now my 2 questions: Why does dircache.listdir() work different?
3
1305
by: =?Utf-8?B?bWFnZ2ll?= | last post by:
hi, I've been working getting a file parsed out using Regex. There's something I don't understand. When I define the pattern for my fields in my file, I am telling regex to grab those fields ( strings and salary figures, numbers with decimals) . Some of the fields contain commas, so that's why I'm using Regex. This is a comma-delimited file. I am not understanding the Split command. Right now , my file is being split into 4 occurrences,...
4
1879
by: tonywh00t | last post by:
Hi everyone, I have a "simple" question, especially for people familiar with regex. I need to parse strings that have the form: 1:3::5:9 which indicates the set of integers {1 3 4 5 9}. In other words i have a set of numbers separated by ":", where "::" indicates a range from lo to hi inclusive. It is desirable to error check this string (i.e it
0
9645
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
9480
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
10325
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...
1
10091
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
8972
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...
0
5381
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...
1
4053
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
2
3646
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
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.