Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python open() function issue

I am having a problem with a file i am writing too, basically what i want it to do is, i got a input() saying "enter your name: " stored in a variable, now i created the file wrote what i wanted and based on what the person has input() i wanna place that information into the file on a specific line...

This is what i did to do it and it works, but it is overwriting current text rather then inserting the text and shifting the current text over...

eg;

index = open('index.html' 'w')
index.write(""" blah blah blah
                blah blah blah
                blah """)
index.seek(20)
index.write(variable)
index.close()

now all i want the variable to do is go into the file like it is doing but not overwrite current text, any advice would be appreciated.

I am using Python3.2.

like image 701
thechrishaddad Avatar asked Nov 27 '25 14:11

thechrishaddad


1 Answers

To insert text into a file, read in the text from the file into a variable. Insert the text in the correct place, and then write the text back to the file.

Like so:

with open("filename", 'rt', encoding="utf8") as infile:
    text = infile.read()

text = text[:20] + 'inserted text' + text[20:]


with open("filename", 'wt', encoding="utf8") as outfile:
    outfile.write(text)

However, from your question, I suspect that the file in fact does not exist beforehand, in which case the best way is to simply create the whole text as a variable first, and then write it to file.

like image 129
Lennart Regebro Avatar answered Nov 29 '25 03:11

Lennart Regebro



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!