open() function is used to open a file in Python. It allows you to read data from a file, write new data, append content or create a new file depending on the mode specified. It returns a file object that can be used to perform file operations.
Example: The following example opens a file in read mode and displays its contents.
f = open("data.txt", "r")
print(f.read())
f.close()
Output
Hello World
Explanation: open("data.txt", "r") opens the file in read mode and f.read() returns the entire contents of the file.
Syntax
open(file, mode="r")
Parameters:
- file: Name or path of the file to open.
- mode: Specifies how the file should be opened.
Return Value: Returns a file object that can be used to read, write or modify the file.
Common File Modes
| Mode | Description |
|---|---|
| "r" | Opens a file for reading (default mode) |
| "w" | Opens a file for writing and overwrites existing content |
| "a" | Opens a file for appending content |
| "x" | Creates a new file and raises an error if it already exists |
| "b" | Opens a file in binary mode |
| "t" | Opens a file in text mode (default) |
Examples
Example 1: The following example creates a new file using x mode. A new file is created only if a file with the same name does not already exist.
f = open("notes.txt", "x")
f.close()
print("File created")
Output
File created
Explanation: open("notes.txt", "x") creates a new file. If notes.txt already exists, Python raises a FileExistsError.
Example 2: The following example writes text to a file and then reads the same file to verify the contents.
f = open("message.txt", "w")
f.write("Python File Handling")
f.close()
f = open("message.txt", "r")
print(f.read())
f.close()
Output
Python File Handling
Explanation: open("message.txt", "w") opens the file in write mode and f.write() stores the text in the file. The file is then reopened using "r" mode to read its contents.
Example 3: The following example appends new content to an existing file without removing the previous data.
f = open("log.txt", "a")
f.write("\nNew entry added")
f.close()
f = open("log.txt", "r")
print(f.read())
f.close()
Output
Application Started
New entry added
Explanation: open("log.txt", "a") opens the file in append mode, so f.write() adds the new text at the end of the existing content instead of replacing it.