Computer Science
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()
Answer
The code given in (a) will open file "practice.txt" in read mode and will read 10 bytes from it. Also, it will not close the file explicitly. On the other hand, the code given in (b) will open file "practice.txt" in read mode and will read the entire content of the file. Furthermore, it will automatically close the file after executing the code due to the with clause.
Related Questions
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.
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 ?
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”
Write a Python program to open the file hello.txt used in question no 6 in read mode to display its contents. What will be the difference if the file was opened in write mode instead of append mode?