## 7.2 Reading and Writing Files 

open() returns a file object , and is most commonly used with two arguments: open(filename, mode) . 

>>> f =open('workfile','w') 

The first argument is a string containing the filename. The second argument is another string containing a few char- acters describing the way in which the file will be used. mode can be$_{'r'}$ when the file will only be read,$_{'w'}$ for only writing (an existing file with the same name will be erased), and$_{'a'}$ opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted. 

Normally, files are opened in text mode , that means, you read and write strings from and to the file, which are encoded in a specific encoding. If encoding is not specified, the default is platform dependent (see open() ). 'b' appended to the mode opens the file in binary mode : now the data is read and written in the form of bytes objects. This mode should be used for all files that don’t contain text. 

In text mode, the default when reading is to convert platform-specific line endings ( 
 on Unix, \r
 on Windows) to just$_{
}$. When writing in text mode, the default is to convert occurrences of$_{
}$ back to platform-specific line endings. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. 

It is good practice to use the$_{with}$ keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using$_{with}$ is also much shorter than writing equivalent$_{try}$-$_{finally}$ blocks: 

>>>with open('workfile') as f: ... read_data=f.read() >>> # We can check that the file has been automatically closed. >>> f.closed True 

If you’re not using the$_{with}$ keyword, then you should call$_{f.close()}$ to close the file and immediately free up any system resources used by it. 

Warning: Calling$_{f.write()}$ without using the$_{with}$ keyword or calling$_{f.close()}$ might result in the arguments of$_{f.write()}$ not being completely written to the disk, even if the program exits successfully. 

After a file object is closed, either by a$_{with}$ statement or by calling$_{f.close()}$ , attempts to use the file object will automatically fail. 

>>> f.close() >>> f.read() Traceback (most recent call last): File "<stdin>" , line1, in <module> ValueError: I/O operation on closed file. 

