King
King

Reputation: 65

Unable to write variables (input) to text file

I'm currently writing a simple text editor in python 3.8, I am unable to write the contents of the user input into a file though. When I open the text file in notepad++ a message pops up saying - "This file has been modified by another program, would you like to reload it?". I've tried writing the input to the file as an array but that does not work.

loop = True
    
#Getting file name
filename = input('Filename(Include file extensions) : ')

#Getting What To Write To File
while loop == True:
    text = input('>> ')
    if "EXIT" in text:
        loop = False
        while loop == False:
            #writing to file
            saveFile = open(filename, 'w')
            saveFile.write(text)
            saveFile.close()

Upvotes: 0

Views: 64

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19414

Your loop structure is a bit off. There is no need for using "flag" variables. A more pythonic way is while True: ... break. So your code should look more like this:

#Getting file name
filename = input('Filename(Include file extensions) : ')

#Getting What To Write To File
while True:
    text = input('>> ')
    if "EXIT" in text:
        break

#writing to file
with open(filename, 'w') as saveFile:
    saveFile.write(text)

Of course this will only write the last input with the EXIT, so you might want to make text a list or a queue to perform as a buffer, or just dump directly to the file:

#Getting file name
filename = input('Filename(Include file extensions) : ')

#Getting What To Write To File
with open(filename, 'w') as saveFile:
    while True:
        text = input('>> ')
        saveFile.write(text)
        if "EXIT" in text:
            break

Upvotes: 2

Related Questions