Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract numbers from filename in Python?

Tags:

python

I need to extract just the numbers from file names such as:

GapPoints1.shp

GapPoints23.shp

GapPoints109.shp

How can I extract just the numbers from these files using Python? I'll need to incorporate this into a for loop.

like image 312
Borealis Avatar asked Dec 23 '12 03:12

Borealis


People also ask

How do I get the input of a filename in Python?

inputFileName = input("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") 1. Open the file and associate the file with a file variable (file is “locked” for writing). 2.

How do I extract just the numeric value of a string in Python?

This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.


1 Answers

you can use regular expressions:

regex = re.compile(r'\d+')

Then to get the strings that match:

regex.findall(filename)

This will return a list of strings which contain the numbers. If you actually want integers, you could use int:

[int(x) for x in regex.findall(filename)]

If there's only 1 number in each filename, you could use regex.search(filename).group(0) (if you're certain that it will produce a match). If no match is found, the above line will produce a AttributeError saying that NoneType has not attribute group.

like image 70
mgilson Avatar answered Oct 09 '22 17:10

mgilson