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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With