Python open() Function — An 80/20 Guide By Example

Python’s built-in open() function opens a file and returns a file object. The only non-optional argument is a filename as a string of the file to be opened. You can use the file object to access the file content. For example, file_obj.readlines() reads all lines of such a file object.

Here’s a minimal example of how the open() function

f_obj = open('code.py')
print(f_obj.readlines())

Assuming you store this code snippet in a file called 'code.py', it opens itself and stores its contents in a list of string. This is the output of the code:

["f_obj = open('code.py')\n", 'print(f_obj.readlines())\n']

Python open() Video

Python open() Syntax

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
ArgumentfileString. The name of the file to be opened.
modeOptional string. Mode in which to open the file (see below).
bufferingOptional integer. Buffering policy: set 0 in binary mode to switch buffering off or 1 in text mode to select line buffering. Any integer > 1 indicates the byte size of a fixed-size chunk buffer.
encodingOptional string. Name of encoding to decode or encode the file (text mode only).
errorsOptional string. Defines handling of encoding and decoding errors (see Error Handlers).
newlineOptional string. How universal newlines mode works. Possible values: None, '', '\n', '\r', and '\r\n'.
closefdOptional boolean. Default True. If False and file descriptor rather than filename given as first argument, the file descriptor will be kept open when file is closed.
openerOptional opener. A custom opener defined as callable returning file descriptor. File object is then obtained by calling opener(file, flags).
Return Valuefile_objectAn object exposing the corresponding file resource with methods such as read() or write().

You can use the following file modes:

ModeMeaning
'r'Reading
'w'Writing + overwriting if file exists
'x'Exclusive creation. Fails if file exists
'a'Writing + appending if file exists
'b'Binary mode
't'Text mode
'+'Updating (reading and writing)

Example: How to Open a File and Read all Lines?

Let’s go over the different file modes and ways to use the Python open() function—in a highly random but, hopefully, educational manner.

You’ve already seen the most basic way to use the open() function:

f_obj = open('code.py')
print(f_obj.readlines())

This opens the file 'code.py' and reads all lines from the file. Per default, the file opens in read-only mode. So, the following call with the specifier 'r' is semantically identical:

f_obj = open('code.py', mode='r')
print(f_obj.readlines())

As it’s a positional argument, the following call is also identical:

f_obj = open('code.py', 'r')
print(f_obj.readlines())

The output of these three variants is the same—assuming the code is stored in a file 'code.py':

["f_obj = open('code.py', 'r')\n", 'print(f_obj.readlines())\n']

Example: How to Open a File and Write a String?

You can open a file in write mode using the open(filename, 'w') function call in 'w' writing mode. This creates the file with filename—or overwrites the file if it already exists. By calling f_obj.write(string) on the newly-created file object, you can write an arbitrary string into the file. Now, please don’t forget to close the file using f_obj.close() because only then you can be sure that the written string is actually flushed into the file!

Here’s the code:

f_obj = open('text.dat', 'w')
f_obj.write('hello world')
f_obj.close()

The code creates a new file 'text.dat' and writes the string into it. The resulting file looks like this:

ATTENTION: If you had previously created this file, opening the file in 'w' writing mode overwrites all existing content! ALL CONTENT CAN BE LOST!

Instead, you may want to prefer the append mode when opening your file:

Example: How to Open a File and Append a String?

You can open a file in append mode using the open(filename, 'a') function call. This creates the file with filename. By calling f_obj.write(string) on the newly-created file object, you can write an arbitrary string into the file. If the file already exists, it simply appends the string to the end of the file. Again, don’t forget to close the file using f_obj.close() because only then you can be sure that the written string is actually flushed into the file!

Here’s the code:

f_obj = open('text.dat', 'a')
f_obj.write('\nhi universe')
f_obj.close()

The code appends the string '\nhi universe' to the content already written to 'text.dat' (see previous example). The resulting file looks like this:

Note the newline character '\n' that now appears as a newline in the editor. You need to explicitly define the newline character if you want to append content in a new line at the end of an existing file.

If the file doesn’t exist yet, the append mode works just as the writing mode.

Summary

Python’s built-in open() function opens a file and returns a file object. The only non-optional argument is a filename as a string of the file to be opened. You can use the file object to access the file content. For example, file_obj.readlines() reads all lines of such a file object.

Here’s a minimal example of how the open() function

f_obj = open('code.py')
print(f_obj.readlines())

Want to keep improving your Python skills? Check out our free Python cheat sheets:

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!