Detailed Explanation of the Example of Reading the Numbers in the Filename in Python

  • 2021-08-31 08:36:40
  • OfStack

When we use the computer, we create a folder, which can save desktop space and do a good job of sorting and summarizing. In python, each file has different contents. If we want to use the file, we have to read the file. This article introduces the method of Python reading the numbers in the file name: 1. Use regular expressions; 2. Get the matching string; 3. If you need integers, you can use int;; 4. Generate numbers.

Step 1: You can use regular expressions


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

Step 2: Then get the matching string


regex.findall(filename)

This will return a list of strings containing numbers.

Step 3: If you actually need integers, you can use int


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

Step 4:

If there is only one number in each file name, you can use regex. search (filename). group (0) if you are sure it will produce a match.

If no match is found, the row above generates an attributeError, indicating that NoneType does not have attributegroup.


import re
name = 'CP_epoch164.pth'
regex = re.compile(r'\d+')
num = int(max(regex.findall(name)))
print(num)

Note: The return value of regex. findall (name) is list, so the value is taken and rounded by the max function.


Related articles: