+ 4

[Python] Why doesn't this code work?

I have an app on my phone called Monospace, which lets me make simple notes in a monospace font. I tried to make a program that lets me freely create/modify my notes without opening the app, but it doesn't work. Code in answer below. It creates the file, but it doesn't write to it. I tried removing the loop and it worked. Ideas?

14th Apr 2017, 10:01 PM
Supersebi3
Supersebi3 - avatar
10 Respostas
+ 5
Your loop is infinite: 'while True' is always true, so you infinitly input/write, but you never close the file ( so the writing are not validating ), as automatic closing provided by 'with' statement occurs only after the following nested block of code ( so, after your loop, but you never exit it ^^ ).
15th Apr 2017, 2:04 AM
visph
visph - avatar
+ 6
I dont really want the program to terminate though, I just want my input lines to be written to the file. the rest comes later.
14th Apr 2017, 10:17 PM
Supersebi3
Supersebi3 - avatar
+ 5
@visph ohhhh thanks, gonna add some closing command
15th Apr 2017, 8:45 AM
Supersebi3
Supersebi3 - avatar
+ 5
@visph done, works perfectly!
15th Apr 2017, 8:54 AM
Supersebi3
Supersebi3 - avatar
+ 5
@merkrafter thats what it does now, but instead of testing for an empty input, it tests if the input is "quit()"
15th Apr 2017, 12:30 PM
Supersebi3
Supersebi3 - avatar
+ 4
Code: fname = input("What do you want to call your note?\n") fpath = "/storage/emulated/0/Monospace/{}.txt".format(fname) fmode = input("Do you want to overwrite the file or append to it? (w/a)\n") if fmode not in "wa": print("Invalid mode.") quit() print("Now you can freely write to your file!\n") with open(fpath, fmode) as f: while True: inp = input() f.write(inp) f.write("\n")
14th Apr 2017, 10:01 PM
Supersebi3
Supersebi3 - avatar
+ 4
@merkrafter doesnt help, same result as before
14th Apr 2017, 10:09 PM
Supersebi3
Supersebi3 - avatar
- 1
Try to check if the input was empty and if so, jump out of the while loop.
14th Apr 2017, 10:06 PM
merkrafter
- 1
At least your program should terminate and close the file now.
14th Apr 2017, 10:15 PM
merkrafter
- 1
But why didn't it help to end the while loop manually after an if statement?
15th Apr 2017, 12:17 PM
merkrafter