open()
Published Apr 12, 2022Updated Apr 2, 2023
Contribute to Docs
The open()
function is built into Python and can be used for opening files.
Syntax
# First syntax
f = open("file-name.format")
f.close()
# Second syntax
with open("file-name.format") as f:
print("This syntax auto-closes the file.")
As shown above, the open()
function uses two distinct syntaxes:
- The first is assigned to a variable and closed afterwards with the .close() method.
- The second uses the
with
keyword that includes a self-closing function body.
In both cases, file names can be specified in the open()
function. An important point to note is that unless the file exists within the scope of the current directory, the entire file path must be specified.
File Modes
There are several modes Python can do when opening a file. Some commonly-used modes include the following:
'r'
: Reads from an existing file (default mode).'w'
: Writes to a file (initially trims the whitespace).'a'
: Appends the content of an existing file.'x'
: Creates a new file with the provided name string.
Example
Files can be read in either a textual or binary format and denoted as t
and b
, respectively. The default format is text.
open("text.txt") # To open a fileopen("text.txt", 'bx') # Creates a file in binary mode
Codebyte Example
In the example below, multiple calls to the open()
function are made, using several modes to initially create a file with some content and then overwrite it:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours