The "open()" function is a powerful built-in function in Python that is used for working with files. This function allows us to open a file in different modes and perform various operations on it, such as reading from the file, writing to the file, and appending to the file.
The "open()" function takes two arguments: the first argument is the name of the file that we want to open, and the second argument is the mode in which we want to open the file. The mode argument specifies the purpose for which we are opening the file and determines the operations that we can perform on the file. Here are the different modes that we can use with the "open()" function:
Let's take a look at some examples to understand the usage of the "open()" function in Python:
Example 1: Reading from a file
|
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
|
In this example, we are opening the file "example.txt" in read mode using the "open()" function. We then read the entire content of the file using the "read()" method and assign it to the variable "content". Finally, we print the content of the file and close the file using the "close()" method.
Example 2: Writing to a file
|
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
|
In this example, we are opening the file "example.txt" in write mode using the "open()" function. We then write the string "Hello, World!" to the file using the "write()" method. Finally, we close the file using the "close()" method.
Example 3: Appending to a file
|
file = open("example.txt", "a")
file.write("\nThis is a new line.")
file.close()
|
In this example, we are opening the file "example.txt" in append mode using the "open()" function. We then append the string "This is a new line." to the end of the file using the "write()" method. Finally, we close the file using the "close()" method.
In conclusion, the "open()" function in Python is a powerful built-in function that allows us to work with files. This function provides different modes that we can use to open files for reading, writing, and appending, and it also supports binary and text modes for handling different types of files