Skip to content

Instantly share code, notes, and snippets.

@bukowa
Created May 11, 2024 08:18
Show Gist options
  • Save bukowa/cea64ca56a965290bb165e1e94fe4ca1 to your computer and use it in GitHub Desktop.
Save bukowa/cea64ca56a965290bb165e1e94fe4ca1 to your computer and use it in GitHub Desktop.
silent hunter 3 append menu item
import configparser
import os
def replace_second_occurrence(_text, _old, _new):
first_index = _text.find(_old)
if first_index != -1: # If the substring exists
second_index = _text.find(_old, first_index + 1)
if second_index != -1: # If a second occurrence exists
# Replace the second occurrence
return _text[:second_index] + _text[second_index:].replace(_old, _new, 1)
return _text
if __name__ == '__main__':
with open('menu_1024_768.ini') as f:
# use regexp to find each line starting with [G3F I and ending with ]
import re
content = f.read()
matches = re.findall(r'\[G3F I.*\]', content)
print(len(matches))
print(matches)
replaced = 0
for i, match in enumerate(matches):
new = f'[G3F I{i+2}]'
# first occurence of the match
if replaced == 0:
content = content.replace(match, new)
else:
# replace second occurence
content = replace_second_occurrence(content, match, new)
replaced += 1
# save the new content to a new file
with open('menu_1024_768_new.ini', 'w') as f:
f.write(content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment