Python Data Persistence – Opening File
The open ( ) function takes a string corresponding to the disk file’s name along with its path as an argument. The second argument indicates the mode in which the file is intended to be opened. Default file opening is ‘r’ which stands for ‘read’ mode which means data in the file is read into program variables. In order to use the file as the output destination, use ‘w’ as the value of the mode parameter. The function returns a file object.
Example
>>> obj=open( ' test.txt' , 'r') Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> obj =open('test.txt' , ' r ') FileNotFoundError: [Errno 2] No such file or directory: 'test.txt' >>> obj=open('test.txt' , 'w') >>> obj.close() >>>
Noth that when in ‘r’ mode open( ) function can open existing file otherwise raises FileNotFoundError. Always ensure that the opened file object is closed to flush data if any in the buffer.