Spacing For reasonably professional Python code (or for any Python code you or others may have to look at later - ideally, all code you ever write), it would be a good idea to follow the standard PEP 8 style guide, to improve readability. To start with, it recommends putting spaces between arguments and operators, and using 4 spaces for indentation:
pattern = re.compile('<title>RPi Cam Web Interface - Page \d*')
for i in os.listdir():
parser = open(i, 'r', encoding='utf-8')
m = pattern.search(parser.read())
parser.close()
os.rename(i, m.group()[35:] + 'html')
Raw string It's a good idea to use raw strings when creating Python patterns so that escape sequences aren't interpreted, and instead the backslashes are treated as regular characters inside the pattern. For this particular pattern you're using, it happens to not be necessary, but if you ever had to change it and match a newline \n
or a word boundary \b
etc, not having used a raw string would result in the script not running as expected.
In other words, you'd want to do something like:
pattern = re.compile(r'<title>RPi Cam Web Interface - Page \d*')
# ^
Pattern I see 2 issues with the pattern:
- The page number is optional because you're matching with
\d*
instead of \d+
. Using \d+
to match one or more digits would make the intent of the pattern clearer. (\d*
matches "zero or more digits")
- You're manually extracting the page number from the match with
m.group()[35:]
. Use a capturing group in the pattern instead of having to manually count up indicies:
pattern = re.compile(r'<title>RPi Cam Web Interface - Page( \d+)')
# ^^^^^^
# ...
page_number = m.group(1)