text = open(\'samiam.txt\', \'r+\')
keyword = \" i \"
keyword2 = \"-i-\"
replacement = \" I \"
replacement2 = \"-I-\"
for line in text:
if keyword in line:
Use the fileinput module. (See also the MOTW site.)
import fileinput
keyword1 = " i "
keyword2 = "-i-"
replacement1 = " I "
replacement2 = "-I-"
for line in fileinput.input('your.file', inplace=True):
line = line.rstrip()
if keyword1 in line:
line = line.replace(keyword1, replacement1)
elif keyword2 in line:
line = line.replace(keyword2, replacement2)
print line
The fileinput
module, when you use the inplace
option, renames the input file and redirects stdout to a new file with the original file name
If you want to preserve the whitespace on the right of each line, don't rstrip
and use print line,
(note the final comma) to output the processed lines.