I want to search a line and replace a line in a file.txt,
CURRENT_BUILD = 111111
with
CURRENT_BUILD = 221111
Using Python.
I want to search a line and replace a line in a file.txt,
CURRENT_BUILD = 111111
with
CURRENT_BUILD = 221111
Using Python.
You can iterate through the lines in the file, saving them to a list
and then output the list back to the file, line by line, replacing the line if necessary:
with open('file.txt') as f:
lines = f.readlines()
with open('file.txt', 'w+') as f:
for line in lines:
if line == 'CURRENT_BUILD = 111111\n':
f.write('CURRENT_BUILD = 221111\n')
else:
f.write(line)
CURRENT_BUILD = '111111'
print (CURRENT_BUILD.replace('111111', '221111'))
The syntax of replace() is:
str.replace(old, new [, count])
old - old substring you want to replace
new - new substring which would replace the old substring
count (optional) - the number of times you want to replace the old substring with the new substring
If count is not specified, replace() method replaces all occurrences of the old substring with the new substring.
I'm not sure if this is what you meant as you are unclear and haven't shown what the .txt file is but this is replace anyways.
EDIT
if it is in text replace you want then this would be your best bet.
import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')
credit to @jfs from this post How to search and replace text in a file using Python?