text = open(\'samiam.txt\', \'r+\')
keyword = \" i \"
keyword2 = \"-i-\"
replacement = \" I \"
replacement2 = \"-I-\"
for line in text:
if keyword in line:
In your code just replace the line
for line in text:
with
for line in text.readlines():
Note that here I am assuming that the you are trying to add the output at the end of the file. Once you have read the entire file, the file pointer is at the end of the file (even if you opened the file in r+
mode). Thus doing a write will actually write to the end of the file, after the current contents.
You can examine the file pointer by embedding text.tell()
at different lines.
Here is another approach:
with open("file","r") as file:
text=file.readlines()
i=0
while i < len(text):
if keyword in text[i]:
text[i]=text[i].replace(keywork,replacement)
with open("file","w") as file:
file.writelines(text)