| 1. |
Write a note on open( ) function of python. What is the difference between the two methods? |
|
Answer» Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. For Example >>> f = openf’sample.txt”) bopen file in current directory andf is file object >>> f = open(‘c:\ \pyprg\ \chl3sample5.csv’) #specifyingfull path You can specify the mode while opening a file. In mode, you can specify whether you want to read ‘r’ , write ‘w’ or append ‘a’ to the file, you can also specify “text or binary” in which the file is to be opened. The default is reading in text mode. In this mode, while reading from the file the data would be in the format of strings. On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files. f = open(“test.txt”) # since no mode is specified the default mode it is used #perform file operations f.close( ) The above method is not entirely safe. If an exception occurs when you are performing some operation with the file, the code exits without closing the file. The best way to do this is using the “with” statement. This ensures that the file is closed when the block inside with is exited. You need not to explicitly call the close() method. It is done internally. |
|