Computer Science
Why is it advised to close a file after we are done with the read and write operations? What will happen if we do not close it ? Will some error message be flashed ?
Python File Handling
4 Likes
Answer
It is a good practice to close a file once we are done with the read and write operations. When we close a file, the system frees the memory allocated to it. Python ensures that any unwritten or unsaved data is flushed (written) to the file before it is closed. Therefore, it is always advised to close the file once our work is done. If we do not close file explicitly it will close automatically later when it's no longer in use or when the program terminates, without displaying any error message.
Answered By
2 Likes
Related Questions
Write the use and syntax for the following methods:
- open()
- read()
- seek()
- dump()
Write the file mode that will be used for opening the following files. Also, write the Python statements to open the following files:
- a text file “example.txt” in both read and write mode.
- a binary file “bfile.dat” in write mode.
- a text file “try.txt” in append and read mode.
- a binary file “btry.dat” in read only mode.
What is the difference between the following set of statements (a) and (b):
(a)
P = open("practice.txt", "r") P.read(10)
(b)
with open("practice.txt", "r") as P: x = P.read()
Write a command(s) to write the following lines to the text file named hello.txt. Assume that the file is opened in append mode.
“ Welcome my class” “It is a fun place” “You will learn and play”