Python open() Function
The open()
function opens a file and returns it as a file object. With this file object you can create, update, read, and delete files.
Syntax
open(file, mode, buffering, encoding, errors, newline, closefd, opener)
open() Parameters
Python open()
function parameters:
Parameter | Condition | Description |
---|---|---|
file | Required | The path and name of the file |
mode | Optional | Specifies the mode you want to open the file |
buffering | Optional | Sets the buffering policy |
encoding | Optional | Specifies encoding |
errors | Optional | Specifies different error handling scheme |
newline | Optional | Controls how universal newlines mode works |
closefd | Optional | Keeps the underlying file descriptor open when the file is closed |
opener | Optional | A custom opener used for low-level I/O operations |
Note that if mode
to open a file is not specified, then the default 'rt'
(open for reading in text mode) is used.
Possible file modes are the following:
Character | Mode | Description |
---|---|---|
'r' | Read (default) | Open a file for read only |
'w' | Write | Open a file for write only (overwrite) |
'a' | Append | Open a file for write only (append) |
'r+' | Read+Write | open a file for both reading and writing |
'x' | Create | Create a new file |
You can also specify how the file should be handled.
Character | Mode | Description |
---|---|---|
't' | Text (default) | Read and write strings from and to the file. |
'b' | Binary | Read and write bytes objects from and to the file.This mode is used for all files that don’t contain text (e.g. images). |
open() Return Value
Python open()
function returns a file object, which can be used to read from, write to, or modify the file.
If the file is not found, it raises the FileNotFoundError
exception.
Examples
Example 1: Open a File
This example demonstrates how to open a file in read mode, read its contents, and then close the file.
f = open("demofile.txt")
print(f.read())
f.close()
Since the mode is omitted, the file is opened in 'r' mode. This is equivalent to the following code:
f = open("demofile.txt", "r")
print(f.read())
f.close()
Example 2: Open a File with a different encoding
To open a file with a different encoding, you can just specify the encoding parameter of open()
function.
In the following example, we use 'utf-8'
encoding.
f = open("demofile.txt", mode = 'r', encoding='utf-8')
print(f.read())
f.close()
Example 3: Creating a New File
This example creates a new file named newfile.txt
and writes some text to it, demonstrating the exclusive creation mode.
Note that here the 'x'
file mode is used.
Using 'x'
file mode, if newfile.txt
already exists, the operation will fail, and no file will be created or modified.
f = open("newfile.txt", "x")
print(f.read())
f.close()
Example 4: Writing to a File
This example shows how to open a file in write mode, write some text to it, and then close the file.
Note that here the 'w'
file mode is used.
f = open("demofile.txt", "w")
f.write("Hello, World!")
f.close()
Example 5: Appending to a File
This example demonstrates appending text to an existing file by opening it in append mode.
Note that here the 'a'
file mode is used.
f = open("demofile.txt", "a")
f.write("\nThis line was added later.")
f.close()
Example 6: Opening a File in Binary Mode
This example opens an image file in binary mode for reading, allowing you to process the file's binary content.
f = open("image.jpg", "rb")
# Process the binary file content ...
f.close()
Example 7: Opening a File using with
statement
This example demonstrates how to use the with
statement to read to a file, ensuring that the file is properly closed after the operation is complete.
This approach is cleaner and more Pythonic than manually opening and closing the file!
with open("demofile.txt", "r") as file1:
print(file1.read())
You do not need to close the file manually by invoking file1.close()
because it is automatically done at the end of the with
statement!
Example 8: Opening Two Files Simultaneously
To combine multiple file access modes for the open()
function in Python, you can use the with
statement to open multiple files simultaneously.
This allows you to manage file operations efficiently, ensuring that all files are properly closed after the operations are completed.
In the following example:
file1.txt
is opened in read mode ('r'
), allowing the program to read its contents.file2.txt
is opened in write mode ('w'
), enabling the program to write to this file.- The
with
statement ensures that both files are properly closed after the block of code is executed, even if an error occurs during the file operations.
try:
with open('file1.txt', 'r') as file1, open('file2.txt', 'w') as file2:
content = file1.read()
file2.write(content)
except IOError as e:
print('Operation failed:', e.strerror)
output
Example 9: Merging Two Files into a Third File
This example shows how to merge the contents of two files into a third file.
It reads from file1.txt
and file2.txt
, and writes the combined content into file3.txt
.
In this example:
- Both
file1.txt
andfile2.txt
are opened in read mode ('r'
). file3.txt
is opened in write mode ('w'
), allowing the program to write the combined content of the first two files into it.- The
with
statement manages the opening and closing of all three files, ensuring resources are properly managed.
try:
with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2, open('file3.txt', 'w') as file3:
content1 = file1.read()
content2 = file2.read()
file3.write(content1 + "\n" + content2)
except IOError as e:
print('Operation failed:', e.strerror)
output