text = open(\'samiam.txt\', \'r+\')
keyword = \" i \"
keyword2 = \"-i-\"
replacement = \" I \"
replacement2 = \"-I-\"
for line in text:
if keyword in line:
It is because you are trying to read and write at the same time. Try something like:
# Read operation
lines = []
for line in text.readlines():
if keyword in line:
lines.append(line.replace(keyword, replacement))
print line
elif keyword2 in line:
lines.append(line.replace(keyword2, replacement2))
print line
else:
lines.append(line)
print line
text.close()
# Write operation
text = open('dummy.py', 'w+')
text.writelines(lines)
text.close()
Bonus:
with open('data.txt') as f:
data = f.read()
is more pythonic.