Python Read and Write Files

Sometimes you need to work with external files in Python. Perhaps you want to read a configuration file from a network device or you need to parse a log file. Fortunately, Python can read and write files.

Open() Function

To work with files in Python, we need to use the open() function. There are three options to work with files:

  • Read (r): This is the default option which opens a file to read.
  • Write (w): Open a file and write to it. Overwrites any current content in the file.
  • Append (a): Opens the file and writes to it but instead of overwriting, appends to the file.

Python can work with text or binary (JPG, PNG, MP3, etc.) files.

Let’s see what we can do.

Open File

I’ll create a text file named “demo.txt” with the following contents:

In our code, we didn’t specify whether we wanted to read, write, or append to the file. We also didn’t specify whether we wanted to open it in text or binary mode. We don’t have to because the default options are “r” (read) and “t” (text). If you do want to specify our options, it looks like this:

So far, so good. We have the contents of our file. However, Python returned it as a string. Wouldn’t it be easier if each line was a separate string? We can do this with the readlines() function:

Run the code above, and it shows each line as a string within a list.

Close File

In the example above, we opened a file but we never closed it. Closing files is important, especially when you write files.  Some changes in files won’t show up until you close them. In Microsoft Windows, open files are locked which prevents other programs from opening or writing to your files. Here’s an example of how to close your file:

First, we open the file, then we do something with it, and finally, we close the file.

With Open

Instead of using the separate open() and close() function, we can also use the with block. You put everything you want to do with the file under the with block, and afterward, Python automatically closes the file. Here is an example:

I personally prefer this way. The indentation makes it easier to recognize what you do with the file in your code and you don’t have to worry about not closing the file.

Write File

When you write to a file, you overwrite its contents. When the file doesn’t exist, Python creates the file. To write to the file, we need to add the “w” parameter to the open() function. Here is our code:

The code above writes a string to the “demo2.txt” file. We could use a text editor to check the contents of the file but since we are using Python, we’ll open it in Python as well.

If you run this code multiple times, it always shows a single line. That’s because the write parameter overwrites the content of our file.

Append File

Instead of overwriting the content of our file, we can append to the file. To do this, you have to use the “a” parameter in the open() function:

When we run the above code multiple times, you’ll see that Python appends the string to our file. There is one problem though. Python appends the string to the same line.

New Line

If you want to append to a new line, you have to use the \n new line symbol in your string. Here’s our code:

In the code above, I added the \n new line symbol before my string. Each line we append is now saved in a new line of our file.

Unlock This Lesson for Free - No Payment Required!

If you like to keep on reading, register now!

  • Learn CCNA, CCNP and CCIE R&S. Explained As Simple As Possible.
  • Get Instant Access to this Full Lesson, Completely for Free!
  • Unlock More to Read. More Lessons Added Every Week!
  • Content created by Rene Molenaar (CCIE #41726)
2126 Sign Ups in the last 30 days

Forum Replies

  1. Hello, Rene, Nice lession"

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

  2. 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:

    Line1
    Change This Line
    Line3
    

    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")
    a_file.writelines(list_of_lines)
    a_file.close(
    ... Continue reading in our forum

  3. 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 ?

  4. 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:

    https://linuxhint.

    ... Continue reading in our forum

Ask a question or join the discussion by visiting our Community Forum