How this file can be closed. Any idea?
with open('output.txt','w', encoding='UTF-8') as output:
output.writelines(str(i)+'\n' for i in range(5))
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The file is automatically closed when you leave the “
with-block” or an exception is encountered. This is why it’s the preferred way to open files.See this PEP 343 — The “with” Statement for more information on the
withstatement. The Python “with” Statement by Example gives more information.UPDATE:
Your inability to delete a file opened with
withwas due to the file having been left open previously (when not usingwithand not explicitlycloseing it). As a test using a different file andwithdidn’t create a problem.