Today, I'm going to write about ways of reading contents of a file using python 3. There are two common ways to do this. A not so good way and a better way. Further, we will also see how to copy contents of one file into other file.
We will work with a file named "acetylene.xyz". The contents of this file is as follows:
Reading a file METHOD 1: Not so good wayUsing try/ finally one can read as follows:
In the above code, we called inbuilt function open( ) which takes filename as a necessary argument. You can also provide 'r', 'w', 'a' i.e. read write append etc. as optional arguements. The function, open( ) also takes encoding ('UTF8', 'ASCII' etc.) as an optional argument.When you don't mention the encoding, python uses locale.getpreferredencoding( ) to determine your environment's default encoding.
Executing the above piece of codes indeed gives the expected output.
Reading a file METHOD 2: A better way
Here we will use the with statement which was introduced in python 2.5 as a replacement for try/finally (see PEP 343). We can read the same file using with statement as follows:
The above code gives the same output as method 1:
In Method 2, the file is open when you are within the code block of with statement. The moment you leave this code block, python closes the file for you by calling a_file.close( ). You don't have to do it yourself as in method 1.
Now you'd be wondering why I say that method 2 is better than method 1. Mark Pilgrim in his book Dive Into Python 3 explains as follows:
"Stream objects have an explicit close( ) method, but what happens if your code has a bug and crashes before you call close( )? That file could theoretically stay open for much longer than necessary. While you’re debugging on your local computer, that’s not a big deal. On a production server, maybe it is."
How to copy contents of one file into other file?
Using the above code, the file "acetylene.xyz" is copied into a backup directory. The name of backup file will also be acetylene.xyz (because we did not mention file name, backup was an already existing directory).
AcknowledgementSpecial thanks to +wesley chun (author, core python programming) for his valuable suggestions on improving this post.