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 strings.
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)
Argument | file | String. The name of the file to be opened. |
mode | Optional string. Mode in which to open the file (see below). | |
buffering | Optional 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. | |
encoding | Optional string. Name of encoding to decode or encode the file (text mode only). | |
errors | Optional string. Defines handling of encoding and decoding errors (see Error Handlers). | |
newline | Optional string. How universal newlines mode works. Possible values: None , '' , '\n' , '\r' , and '\r\n' . | |
closefd | Optional 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. | |
opener | Optional opener. A custom opener defined as callable returning file descriptor. File object is then obtained by calling opener(file, flags) . | |
Return Value | file_object | An object exposing the corresponding file resource with methods such as read() or write() . |
You can use the following file modes:
Mode | Meaning |
---|---|
'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 can you 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 can you 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.
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:
👉 Recommended Tutorial: How to Return a File From a Function in Python?
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. 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?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming 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.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.