Python Read and Write Files

This topic is to discuss the following lesson:

Hello, Rene, Nice lession"

What if I want remove some string or text within the file, without delete the file itself ? Is it possible?

Hello Stefanio

Yes it is possible to delete a particular line within a file. Specifically, you must call file.readlines() to get a list of all the lines in that file. You can then use list indexing to edit a specific line. You can do it like so:

Let’s say you have a text file called my_text.txt that contains the following lines:

Change This Line

Use the following code:

a_file = open("my_text.txt", "r")
list_of_lines = a_file.readlines()
list_of_lines[1] = "Line2\n"

a_file = open("my_text.txt", "w")

The resulting contents of my_text.txt is:


I hope this has been helpful!


1 Like

Hi Rene,

Let’s say my file has show interface status command output of the switch. If I only want to display the ports that are connected, is there a function or functions I can use to filter only connected ports in the file ?

Hello Ripal

I believe the easiest way to achieve this is to use Cisco’s CLI output modifiers. You can use the show interface status | include connected command to limit the output to only the connected ports. You can create different Python functions to call different CLI commands according to the kind of output you want.

Creating a Python script to filter out the connected interfaces is possible, but it is definitely more complicated. If you want to achieve it via Python, there are many ways to do it. Some are found at the following link:

I hope this has been helpful!