#

Monday, May 5, 2025

Handling Text Files in Python for Network Engineers

Opening & Closing a Text File

Following code is the classic way of opening and closing a text file.

1st line opens a file which is in the current directory and the other line closes the file.


Since the above way always needs the closing statement to close the file, the better Pythonic way of doing this is to use a context manager. A context manager is a construct that properly manages the setup and teardown of resources like files, network connections, or locks using the with statement.

This way, when you exit from the indentation, the file is closed automatically.



Above code opens the file and save it in the memory as "f" and reads it and stores it in the variable called "output" and prints it out. Basically it prints the text file contents to the CLI.

Following is the sample.txt file in the working directory and let's run the above to see the output.







Output will be:





If we want to get the lines into a List,





Output will be:



Writing to a Text File

Following syntax will write a text to a file.

"w" implies that the file is opened to write, default it read only.


But this actually overwrites the file, so following will be the contents inside the file.





Instead we can append the text we want by opening the file with "a" append mode.





Output will be:
By proper spacing, using \n for line breaking, we can form the text much better.



Following example shows how we can write a file with List of data using f.writelines() method.






Output will be like the following..





Following sample code open 2 files and file and copy the contents of the source file to the destination file after manipulating the text. This is the advantage of copying it to memory. This example capitalizes the letters in the text.






Output will be:






Note:- Even though we need a file with the specified name already to work with reading, that is not the case for writing, It creates a new file if it does not exist.

Note:- 
If we want to read or write a file in another directory, we should give the path like the following.





Since forward slash (/) is used in Linux and back slash (\) is used in Windows, writing scripts to match the host OS can be problematic, Because of this, following piece of code helps to build the directory path according to the OS.







Since my one is Linux, output is:

No comments:

Post a Comment