I want to replace certain lines in my text with another string. So far I was able to locate the text I want to replace with:
text = open('sample','r').read()
regex = re.compile('.*#= min, max\s')
for match in regex.finditer(text):
print match.group(0) #this is what i want to replace
EDIT: also tried
text = open('sample','r').read().split('\n')
for line in text:
line = re.sub('.*#= min, max\s', "HOLA", line)
The text stays the same. Could it be that my regex is messed up? I used the same one somewhere else and there was no problem. Also its a simple regex.
How do I switch it to another line? Thanks!
try:
subbedlines = []
with open('sample','r') as textreader:
lines = textreader.read().split('\n')
for line in lines:
subbedlines.append(re.sub('.*#= min, max\s', "HOLA", line))
should work if your regex is correct and your lines in the text file are matching. to write the file again simply do:
with open('sample','w') as textwriter:
for line in subbedlines:
textwriter.write("%s\n" % line)
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