Kieran
Kieran

Reputation: 25

Python [2.7.11] user input and writing to file

Hello for some reason I cant get this code I am working on to just add a new line to the html document, I am new a python just started coding yesterday, I mainly work with ms-dos but that's not actaly a language.

anyhow what the code is doing is is taking user input and output to the chat.html file, i have it on a loop so people can still add words to the file, however It will replace that line of the file on every new word.

I have tried looking on YouTube for bits of code that may work as well as many forums and help docs by python, nothing seems to work for what ever reason.

Below you can find the code that I am working with, no doubt its something relay simple that I don't know about yet.

while 1:
    userinput = raw_input('Message:')
    myfile = open('./chat.html', 'w')
    myfile.write(userinput)
    myfile.close()
    if userinput == 'exit': break

Upvotes: 0

Views: 227

Answers (4)

Paul Rooney
Paul Rooney

Reputation: 21609

Why not just open the file outside the loop once?

with open('./chat.html', 'a') as myfile:
    while 1:
        userinput = raw_input('Message:')

        if userinput == 'exit':
            break

        myfile.write('{}\n'.format(userinput))

Closing is taken care of by using with

Upvotes: 1

JustDucky
JustDucky

Reputation: 132

You may want to take advantage of the "with" keyword to open and close files. Here's how I would do it:

while True:
    userInput = raw_input("Message: ").lower()
    if userInput == 'exit':
        break #or sys.exit() if you want
    else:
        with open('./chat.html', 'a') as myfile:
            myfile.write(userInput)

Upvotes: 0

Goel
Goel

Reputation: 1

I think we are misunderstanding what the OP is really asking for.

He/she is asking to see if there is a solution to the issue which overwrites the contents within the "./chat.html" file for every new word he/she enters.

The easiest fix to this issue is as stated below:

    while 1:
        userinput = raw_input('Message:')
        if userinput == 'exit':
            exit()
        myfile = open('./chat.html', 'a')
        myfile.writelines(userinput)
        myfile.close()

Upvotes: 0

user2823297
user2823297

Reputation: 37

You open file once outside the while loop and then check for the condition. Or you can open the file in append mode so that it wont overwrite the previous contents.

Upvotes: 0

Related Questions