Reputation: 35
So I wrote a script which gets parameters from input (by hand) and it writes it in a text file. My only problem is that the text from the input won't appear in the txt file, only if i restart the shell manually. What would you recommend to try to fix this, so I don't have to restart the the shell manially all the time?
Well the script is simple, because I'm beginer :D
# input to txt
text_from_input = input()
file=open("testfile.txt","w")
file.write(text_from_input)
file.close
Upvotes: 1
Views: 70
Reputation: 104792
In your code, you're referencing the close
method of your file object, but you're not calling it. That means the file isn't closed until you close the interpreter (you could probably also get the same effect by using del file
or rebinding the variable to some other object).
To fix the problem, you can call close
just by adding parentheses: file.close()
Or better yet, use a with
statement:
with open("testfile.txt","w") as file:
file.write(text_from_input)
# the file will be closed here
When the indented block following the with
ends, the file will be closed automatically. It will happen even if you exit the block unexpectedly, due to an exception.
Upvotes: 3