- Picked, Python, Python-Built-in-functions

Python open() Function

The python open() function is used to open() internally stored files. It returns the contents of the file as python objects.Syntax: open(file_name, mode) Parameters:file_name: This parameter as the name suggests, is the name of the file that we want to open.mode: This parameter is a string that is used to specify the mode in which the file is to be opened. The following strings can be used to activate a specific mode:“r”: This string is used to read(only) the file. It is passed as default if no parameter is supplied and returns an error if no such file exists.“w”: This string is used for writing on/over the file. If the file with the supplied name doesn’t exist, it creates one for you.“a”: This string is used to add(append) content to an existing file. If no such file exists, it creates one for you.“x”: This string is used to create a specific file.“b”: This string is used when the user wants to handle the file in binary mode. This is generally used to handle image files.“t”: This string is used to handle files in text mode. By default, the open() function uses the text mode.Example 1: Creating a text fileThe following code can be used to create a file. Here we will be creating a text file named”geeksforgeeks.txt”.Python3created_file = open(“geeksforgeeks.txt”,”x”)  print(open(“geeksforgeeks.txt”,”r”).read() == False)Output:TrueExample 2: Reading and Writing the fileHere we will write the following string to the geeksforgeeks.txt file that we just created and read the same file again.Geeksforgeeks is best for DSAThe below code can be used for the same:Python3my_file = open(“geeksforgeeks.txt”, “w”)my_file.write(“Geeksforgeeks is best for DSA”)my_file.close()  my_file = open(“geeksforgeeks.txt”,”r”)print(my_file.read())Output:Geeksforgeeks is best for DSAExample 3: Appending content to the fileHere we will append the following text to the geeksforgeeks.txt file and again read the same:Python3my_file = open(“geeksforgeeks.txt”,”a”)my_file.write(“..>>Visit geeksforgeeks.org for more!!