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. - import re, os
-
-
files = os.listdir(os.getcwd())
-
#files = ['blue13', 'red011', 'yellow1', 'green1000']
-
-
def getnum(filename): return float(re.findall(r'\d+',filename)[0])
-
def numsort(a,b): return cmp(getnum(a),getnum(b))
-
-
files.sort(numsort)
-
print files
this throws me - 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.
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. - import re, os
-
-
files = os.listdir(os.getcwd())
-
#files = ['blue13', 'red011', 'yellow1', 'green1000']
-
-
def getnum(filename): return float(re.findall(r'\d+',filename)[0])
-
def numsort(a,b): return cmp(getnum(a),getnum(b))
-
-
files.sort(numsort)
-
print files
this throws me - 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: - >>> getnum('split300.py')
-
300.0
-
>>> getnum('xmlscanner.py')
-
Traceback (most recent call last):
-
File "<interactive input>", line 1, in ?
-
File "C:\SDS2_7.0\macro\Work In Progress\re_files_with_numbers.py", line 7, in getnum
-
return float(re.findall(r'\d+',filename)[0])
-
IndexError: list index out of range
-
>>>
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. - import re, os
-
-
files = os.listdir(os.getcwd())
-
#files = ['blue13', 'red011', 'yellow1', 'green1000']
-
-
def getnum(filename): return float(re.findall(r'\d+',filename)[0])
-
def numsort(a,b): return cmp(getnum(a),getnum(b))
-
-
files.sort(numsort)
-
print files
this throws me - 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: - import re, os
-
-
files = os.listdir(os.getcwd())
-
#files = ['blue13', 'red011', 'yellow1', 'green1000']
-
-
def getnum(filename):
-
return float(re.findall(r'\d+',filename)[0])
-
def numsort(a,b):
-
return cmp(getnum(a),getnum(b))
-
-
files.sort(numsort)
-
print files
For example, at first glance I couldn't see these functions.
bvdet 2,851
Recognized Expert Moderator Specialist
Try this: - def getnum(filename):
-
m = re.search(r'\d+',filename)
-
if m: return int(m.group(0))
-
return None
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. -
import re,os
-
-
files = os.listdir(os.getcwd())
-
#files = ['blue13', 'red011', 'yellow', 'green1000']
-
-
def numsort(c,d):
-
def getnum(filename):
-
m = re.search(r'\d+',filename)
-
if m: return float(m.group(0))
-
return None
-
return cmp(getnum(c),getnum(d))
-
-
files.sort(numsort)
-
print files
Thanks again! I'll likely be back!
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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'')
|
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
|
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
|
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.
| |
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.
|
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?
|
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,...
|
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
|
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...
|
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,...
| |
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...
|
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,...
|
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...
|
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...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |