python-regexHow to replace in a file using Python regex?
Regex (Regular Expressions) can be used to replace text in a file using Python.
import re
# open the file
f = open('file.txt', 'r')
# read the file
text = f.read()
# close the file
f.close()
# replace the text
text = re.sub('old_text', 'new_text', text)
# open the file
f = open('file.txt', 'w')
# write the new text
f.write(text)
# close the file
f.close()
The example code above will open a file, read the contents, replace the text, and write the new text back to the file.
Code explanation
import re
- imports the regular expression modulef = open('file.txt', 'r')
- opens the file in read modetext = f.read()
- reads the contents of the filef.close()
- closes the filetext = re.sub('old_text', 'new_text', text)
- replaces the text using the regular expression modulef = open('file.txt', 'w')
- opens the file in write modef.write(text)
- writes the new text to the filef.close()
- closes the file
Helpful links
More of Python Regex
- How to replace all using Python regex?
- How to count matches with Python regex?
- How to match a year with Python Regex?
- How to perform a zero length match with Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to match a hex number with regex in Python?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
See more codes...