Using with in Python

It is Wednesday in the Twin Cities of Minneapolis and St. Paul. My wife and I spent most of the morning dealing with health insurance. Hopefully all will be done in the next few days. I am in the process of changing health insurance companies. Due to the COVID-19 pandemic everyone is using some type of video application to communicate. The proposed application was Zoom, but due to the security issues, we prefer using Jitsi. It did not take more than a minute to switch applications. It is interesting that video on Jitsi was working great but one of the participants decided to use our cell phones for voice because he did not have a camera or microphone on his computer. The cellular signals were not that great, but we managed.

Earlier today I watched on YouTube a video from Channel 9 – Microsoft Developer named Demo: Using with | More Python for Beginners [17 of 20].

As usual I experimented with the code being presented.

# file: demo.py

# **** ****
fileName = "output.txt"
text = "This is a test. That's all folks"

# **** open and write to the specified file ****
try:
    stream = open(fileName, "wt")
    stream.write(text)
finally:
    stream.close()

Using VSCode I wrote the Python code shown above.

The name for the output file is output.txt which implies that the expected output will be in the same folder were the code will be executing.

In a try: finally: we open the text file and write some text to it. The finally: clause will always execute even if we are not able to open the file. In this case we assume we will be able to open the output file. If the output file would be in a different and non-existing drive (e.g., X:\Data\output.txt) or non-existing folder (e.g., C:\Cake\output.txt), the open operation would have thrown an exception.

PS C:\Users\johnc\workspace0\UsingWithPython> python demo.py
PS C:\Users\johnc\workspace0\UsingWithPython> type output.txt
This is a test. That's all folks
PS C:\Users\johnc\workspace0\UsingWithPython> 

If we write the output file to the directory holding the demo.py file, then we can use the TERMINAL in VSCode to read the contents of the file.

# **** file: demo.py ****

# **** import libraries and classes ****
import os


# **** file to write ****
fileName = "output.txt"

# **** text to write ****
text = "This is a test. That's all folks"

#**** open and write to the specified file ****
# try:
#     stream = open(fileName, "wt")
#     stream.write(text)
# finally:
#     stream.close()

# **** open and write to the specified file (automatically closes stream) ****
with open(fileName, "wt") as stream:
    stream.write(text)


# **** file to read ****
fileName = "c:\\temp\\README.txt"

# **** open and read the specified file ****
try:
    with open(fileName, "rt") as stream:
        while True:
            line = stream.readline()
            if not line:
                break
            line = line.rstrip()
            if line == "":
                continue
            print(f"line ==>{line}<==") except OSError: print(f"open fileName ==>{fileName}<== exception OSError") os._exit(-1) except: print(f"open fileName ==>{fileName}<== failed")
    os._exit(-1)

The demo.py file has been edited to use the “with” statement. In this case we do not need to explicitly close the stream. The stream will be closed automatically as soon as the “with” statement is completed. This results in smaller and simpler code.

Next we specify a different file to read. If we do not enclose the “with” statement with a try: except: pair, if an exception occurs it would not be caught. In our case we will be able to catch an exception.

If all is well we would read all the lines in the text file. If the line is blank we would skip it. Non-blank lines are displayed.

PS C:\Users\johnc\workspace0\UsingWithPython> python demo.py            
line ==>Windows 10 Couldn't start client Java Language Server even with java_home set #785<== line ==>https://github.com/redhat-developer/vscode-java/issues/785<== line ==>c:\temp\jdk-8u241-windows-x64.exe<== line ==>c:\Program Files\Java\jdk1.8.0_0241<== line ==>c:\temp\jre-8u241-windows-x64.exe<== line ==>C:\Program Files\Java\jre1.8.0_241<== line ==>in Path:<== line ==>C:\Program Files (x86)\Common Files\Oracle\Java\javapath;<== line ==>C:\Program Files\AdoptOpenJDK\jdk-11.0.6.10-hotspot\bin;<== line ==>c:\sencordist\bin;<== line ==>c:\sdm\bin;<== line ==>%SystemRoot%\system32;<== line ==>%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%SYSTEMROOT%\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\npp.7.7.1.bin.x64;C:\Program Files\Azure Kinect SDK v1.2.0\tools;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Git\cmd;<== line ==>C:\Users\johnc>where java<== line ==>C:\Program Files (x86)\Common Files\Oracle\Java\javapath\java.exe<== line ==>C:\Program Files\AdoptOpenJDK\jdk-11.0.6.10-hotspot\bin\java.exe<==      

The execution of our program displays all the non-blank lines in the README.txt file.

The entire code for this project can be found in my GitHub repository.

If you have comments or questions regarding this, or any other post in this blog, or if you would like for me to serve of assistance with any phase in the SDLC (Software Development Life Cycle) of a project associated with a product or service, please do not hesitate and leave me a note below. If you prefer, send me a private message using the following address:  john.canessa@gmail.com. I will reply as soon as possible.

Keep on reading and experimenting. It is the best way to learn, refresh your knowledge and enhance your developer toolset!

One last thing, many thanks to all 754 subscribers to my blog!!!

John

Twitter:  @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.