What is Python open() function?
In order to perform input/output (I/O) operations in files, you have to open a file.
The Python open() function is used to open the specified file where you may perform reading, writing, and other operations.
In this tutorial, I will show you how to open a file, read the content of a file, write to a file, and do other related things.
- 1. How to open files in Python?
- 2. An example of reading a file by read method of open() function
- 3. The example of write to file by write() method
- 4. Using the append mode example
- 5. Reading only limited characters in the text file example
- 6. Python read line-by-line example
- 7. An example of readline() method to read line by line
- 8. Reading all lines in a list example
- 9. List of modes
How to open files in Python?
The syntax of using the open() function is:
The parameters of the open function are explained below:
||Specifies the relative or absolute path to the file you want to open. An error (OSError) occurs if the file cannot be opened.|
||Specifies the purpose of opening the file, such as ‘r’ for reading, ‘w’ for writing, and ‘a’ for appending. Detailed mode options are provided in the last section.|
||Sets buffering on or off, using an Integer value. 1 enables text-mode line buffering, and 0 disables buffering in binary mode. This parameter is optional. The default buffering policy is applied if not provided.|
||Applies to text-mode only and specifies universal newlines. Valid values include ‘\n’, ‘\r’, ‘\r\n’, None, and ”.|
An example of reading a file by read method of open() function
In this example, a text file is opened in read-only mode by using the ‘r’ value for the mode parameter in Python open() file function.
The text of the readme.txt file is displayed on the screen.
The readme.txt file is placed at the same location where the Python source file is placed:
# The example of open() functio for reading a text file objFile = open("readme.txt", "r") fileContent = objFile.read(); print ("The text file contains: : ", fileContent) # After performing the operation, close the file objFile.close()
The following things should be noted in the program:
- First of all, the file object is created, and the open() function is used.
- In the open() function, the relative path is given for the readme.txt file.
- The mode parameter is ‘r’, which means opening the file in read-only mode.
- The file content is read by using the Python read() method of the open() function.
- The print function displayed the content of the file.
- Finally, the close() function is used for closing the file.
The example of write to file by write() method
The following example shows using the Python write() method after creating a file object.
In the open() function, the ‘w’ parameter is given for the mode argument.
This enables us to write in a text file, however, the text file will be truncated while using this value. That means the existing text will be removed.
To demonstrate that, the content in the “readme.txt” file initially is “Hello World Python”. This is displayed before opening the file in read-only mode.
After that, the file is opened again in write-only mode, and the write() method is used for adding new text.
The file is closed again and reopened in read-only mode for displaying the content:
# The example of open() functio for reading a text file objRead1 = open("readme.txt", "r") ContFile = objRead1.read(); print ("Content before write() : ", ContFile) # Closing the first instance objRead1.close() #Opening again for write to file objWrite = open("readme.txt", "w") objWrite.write ("Using 'w' for writing text in file") #Closing the file in write mode objWrite.close() #Openging the file again for displaying content after writing objRead2 = open("readme.txt", "r") ContAfterWrite = objRead2.read(); print ("The content after write() : ", ContAfterWrite) objRead2.close()
You can see, the initial text is truncated as we opened the file in write-only mode. The second print function displays only the newly written text.
Using the append mode example
If you require keeping the initial text and avoid truncating this while writing to file then you may use the file append mode.
For that, use the ‘a’ value for the mode parameter. This will append the new text to the end of existing content.
See this example where a few changes are made in the above example. The file text before and after writing the new text is displayed and you can see the difference.
# The example of append mode objRead1 = open("readme.txt", "r") ContFile = objRead1.read(); print ("Content before appending text : ", ContFile) # Closing the first instance objRead1.close() #Open file in append mode objAppend = open("readme.txt", "a") objAppend.write ("Please dont remove the text..\nJust add ahead of existing text! Thanks") #Closing the file in append mode objAppend.close() #Open and read after append(0 objRead2 = open("readme.txt", "r") ContAfterAppend = objRead2.read(); print ("The content after append() : ", ContAfterAppend) objRead2.close()
The new content is added ahead of the existing text. The newline ‘\n’ is used for writing text in the next line.
Reading only limited characters in the text file example
In all the above examples, the complete content of the text file is read and displayed by using the open() function’s read() method. If you require only a part of the text from the file then you may specify the size in the read() method as follows:
# Read file with size objFile = open("readme.txt", "r") fileContent = objFile.read(10); print ("Reading limited data: ", fileContent) objFile.close()
Reading limited data: Python Hel
By default, the entire content is read and returned (if size is left as in the above examples).
Also, note that the returned data is either string for the text files and bytes object for binary mode.
Python read line-by-line example
You may use a for loop to loop over a file object for reading line by line. Have a look at this example where I wrote a few lines of text in the readme.txt file:
# Read file line by line objFile = open("readme.txt", "r") for linebyline in objFile: print(linebyline, end = '') objFile.close()
Line 1- Python is cool
Line 2- Python is Great
Line 3- Python is Awesome
Line 4- Love it!!!
This way of reading line by line is memory efficient and fast.
An example of readline() method to read line by line
The readline() method can also be used for reading a single line from the file. In that case, the new line character is left at the end of the string. The new line is omitted at the last line.
# Read file readline() objFile = open("readme.txt", "r") print (objFile.readline()); print (objFile.readline()); objFile.close()
Reading all lines in a list example
You may also read all lines in a file to the list. See the example below:
# Read file in list example objFile = open("readme.txt", "r") a_list = list(objFile) print (a_list) objFile.close()
List of modes
|‘r’||Default mode for reading a text file. Allows reading but not writing to the file.|
|‘r+’||Opens the file in both read and write mode, allowing reading and writing to the file.|
|‘w’||Opens a text file in write-only mode. It truncates the content of the file, creating an empty file or overwriting the existing one.|
|‘rb’||Opens the file in binary format for reading only. Used for reading binary data like images or executables.|
|‘rb+’||Binary mode that allows both reading and writing. Suitable for modifying binary files.|
|‘wb’||Opens the file in binary write-only mode. Creates a new binary file or overwrites an existing one.|
|‘a’||Creates a new file if it doesn’t exist. Opens it in append mode for writing at the end of the file, preserving existing content.|
|‘a+’||Opens the file for both reading and appending. Allows reading the existing content and appending new data at the end.|
Useful related reading: The with keyword as doing I/O operations in files.<.