3

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.

2
  • 2
    Why don't you have a template, fill it with the new data and create the whole string dynamically? Commented Jun 18, 2012 at 12:44
  • 3
    You can't actually insert data into a file. Instead you'll need to read the original back in and write out a new one with the additional data output in the desired spot surrounded by the old contents. Commented Jun 18, 2012 at 12:51

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

how do you place the variable in the inserted text bit? do you put quotation marks or just write variable?
Okay it worked thank you, so basically what that code is doing is re reading the file and modifying it then re outputting the file with the new text included, because you cannot just modify the current existing file?
@user1265535: Your first question is answered in the first part of every single Python tutorial in existence. I suggest you go through a tutorial or two before continuing. Yes, you can modify the current existing file. But you can't insert into it, which is obvious once you know how a file works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.