Important Note:
To perform any file operation, the first step is to open the file. Python’s built-in open() function is used to open files in various modes, such as reading, writing, and appending. The syntax for opening a file in Python is −
file = open("filename", "mode")When working with files, you need to specify the mode in which you want to open the file. The mode determines how the file will be used. The most common file opening modes are:

Example of Opening a File in Different Modes:
1.) Read Mode (‘r’) – Opens a file for reading.
# Open a file in read mode
file = open("example.txt", "r")
print(file.read())
file.close()2.) Write Mode (‘w’) – Creates or overwrites a file.
# Open a file in write mode
file = open("example.txt", "w")
file.write("Hello, this is a test file.")
file.close()3.) Append Mode (‘a’) – Adds data to an existing file.
# Open a file in append mode
file = open("example.txt", "a")
file.write("\nAppending new data")
file.close()4.) Exclusive Mode (‘x’) – Creates a new file (Fails if file exists).
try:
# Open a file in exclusive mode
file = open("new_file.txt", "x")
file.write("This is a new file created in exclusive mode.")
file.close()
print("File created successfully!")
except FileExistsError:
print("File already exists, cannot create a new one.")5.) Binary Write Mode (‘wb’) – Writes binary data.
# Open a binary file in write mode
file = open("binary_file.bin", "wb")
file.write(b'Hello')
file.close()
Discussion 0