text = open(\'samiam.txt\', \'r+\')
keyword = \" i \"
keyword2 = \"-i-\"
replacement = \" I \"
replacement2 = \"-I-\"
for line in text:
if keyword in line:
It will be good to use two descriptors - one for reading and other for writing, for readability and single write operation.
text_read = open('samiam.py', 'r').read()
words_replacer_dict = {" i " : " I ", "-i-" : "-I-"}
replaced_text = ""
for line in text_read.split("\n"):
for word, new_word in words_replacer_dict.items():
replaced_text += line.replace(word, new_word)
text_read.close()
text_write = open('samiam.py', 'w')
text_write.write(replaced_text)
text_write.close()
You can even keep a count and write based on count, if you are bothered about memory in this case. Just open the file in read mode with generator expression and keep a reference count to satisfy write operation. NOTE: Read here(not an official link), to learn better about dictionary methods.
However, if you prefer to use read and write, always use seek operation to get to the line that is to be replaced and use flush once you finish writing the file. However, you cannot replace the line that is already there in the file through the seek and flush method. You can merely add something to the file. (eg)
text = open('samiam.py', 'r+')
count = 1
new_text = ""
for line in text:
new_text += "%d:%s\n" % (count, line)
count += 1
text.seek(0)
text.truncate()
text.write(new_text)
text.seek(0)
for line in text:
print line
text.close()
For a better reading on why it is not possible to read and write to file like you wish, please see here