# The following code will search 'MM/DD/YYYY' (e.g. 11/30/2016 or NOV/30/2016, etc ),
# and replace with 'MM-DD-YYYY' in multi-line mode.
import re
with open ('input.txt', 'r' ) as f:
content = f.read()
content_new = re.sub('(\d{2}|[a-yA-Y]{3})\/(\d{2})\/(\d{4})', r'\1-\2-\3', content, flags = re.M)
Answer from Quinn on Stack Overflow# The following code will search 'MM/DD/YYYY' (e.g. 11/30/2016 or NOV/30/2016, etc ),
# and replace with 'MM-DD-YYYY' in multi-line mode.
import re
with open ('input.txt', 'r' ) as f:
content = f.read()
content_new = re.sub('(\d{2}|[a-yA-Y]{3})\/(\d{2})\/(\d{4})', r'\1-\2-\3', content, flags = re.M)
Here is a general format. You can either use re.sub or re.match, based on your requirement. Below is a general pattern for opening a file and doing it:
import re
input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0
for line in input_file:
match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression
if match_br:
br = match_br.group(1)
# Do something
elif match_ot:
ot = match_ot.group(2)
# Do your replacement
else:
output_file.write(line)
python - Replace all regex matches in a file - Stack Overflow
How to edit a text file by using regex (the "sub" function in particular)?
python - How to replace string in a file text based on regex? - Stack Overflow
string - replacing text in a file with Python - Stack Overflow
How do you replace text with a regex pattern in a file?
How do you replace text in the same file in Python?
How do you replace a string in a file using Python?
Use can use the re module to use regular expressions in python and the fileinput module to simply replace text in files in-place
Example:
import fileinput
import re
fn = "test.txt" # your filename
r = re.compile('a(.+?)a')
for line in fileinput.input(fn, inplace=True):
match = r.match(line)
print match.group() if match else line.replace('\n', '')
Before:
hello this
aShouldBeAMatch!!!!! and this should be gone
you know
After:
hello this
aShouldBeAMa
you know
Note: this works because the argument inplace=True causes input file to be moved to a backup file and standard output is directed to the input file, as documented under Optional in-place filtering.
You can use Notepad++ with Version >= 6.0. Since then it does support PCRE Regex.
You can then use your regex a(.+?)a and replace with $1
f = open('greeneggs', 'w')
f.write('i am Sam\nSam i am\nThat Sam-i-am!\nThat Sam-i-am!\ni do not like that Sam-i-am!')
f.close()
import re
with open('greeneggs', 'r+') as text:
redacted_text = re.sub('i', 'I', text)
text.write(redacted_text)I'm trying to replace the lowercase 'i' in each line with uppercase 'I'. It's supposed to be a simple task but I cannot make it work.
I intentionally use a sample of the original "green eggs" because I want to test how it works before adding the whole wall of text. Also, please advice me how to write a lot of text on a txt file by using Python.
- You are opening file with
a->append. So, your changes should be at the end of file. You should create a new file and replace old_one at the end of your script. - There is only one way I know if you want replace several matching groups: first of all you find word using regexp and replace it like a string without regexp.
Thanks Jimilan for your remarks. I fixed my code, and now it`s working:
base_regex = re.compile(.*test_mode.*base_sw=(\S*))
target_regex = re.compile(.*test_mode.*target_sw=(\S*))
for file in self.upgrade_cases_files_list:
file_handle = open(file, 'r')
file_string = file_handle.read()
file_handle.close()
base_version_result = base_regex.search(file_string)
target_version_result = target_regex.search(file_string)
if base_version_result is not None:
current_base_version = base_version_result.group(1)
else:
raise Exception("Could not detect base version in the following file: -> %s \n" % (file))
if target_version_result is not None:
current_target_version = target_version_result.group(1)
else:
raise Exception("Could not detect target version in the following file: -> %s \n" % (file))
file_string = file_string.replace(current_base_version, self.base_version)
file_string = file_string.replace(current_target_version, self.target_version)
file_handle = open(file, 'w')
file_handle.write(file_string)
file_handle.close()
This should do it
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
outfile.write(line)
EDIT: To address Eildosa's comment, if you wanted to do this without writing to another file, then you'll end up having to read your entire source file into memory:
lines = []
with open('path/to/input/file') as infile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
lines.append(line)
with open('path/to/input/file', 'w') as outfile:
for line in lines:
outfile.write(line)
Edit: If you are using Python 2.x, use replacements.iteritems() instead of replacements.items()
If your file is short (or even not extremely long), you can use the following snippet to replace text in place:
# Replace variables in file
with open('path/to/in-out-file', 'r+') as f:
content = f.read()
f.seek(0)
f.truncate()
f.write(content.replace('replace this', 'with this'))