Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I edit a text file in Python?

text = open('samiam.txt', 'r+')
keyword = " i "
keyword2 = "-i-"
replacement = " I "
replacement2 = "-I-"

for line in text:    
    if keyword in line:
        text.write(line.replace(keyword, replacement))
        print line
    elif keyword2 in line:
        text.write(line.replace(keyword2, replacement2))
        print line
    else:
        print line
text.close()

I'm not entirely sure why the text is not being written to the file. help?

like image 241
Andrea Avatar asked Dec 14 '25 09:12

Andrea


1 Answers

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)
like image 149
Prakash Kuma Avatar answered Dec 15 '25 21:12

Prakash Kuma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!