+ 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?
10 Answers
+ 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 ^^ ).
+ 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.
+ 5
@visph ohhhh thanks, gonna add some closing command
+ 5
@visph done, works perfectly!
+ 5
@merkrafter thats what it does now, but instead of testing for an empty input, it tests if the input is "quit()"
+ 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")
+ 4
@merkrafter doesnt help, same result as before
- 1
Try to check if the input was empty and if so, jump out of the while loop.
- 1
At least your program should terminate and close the file now.
- 1
But why didn't it help to end the while loop manually after an if statement?