How to read a text file in PythonPython provides the facility to read, write, and create files. The file can be two types - normal text and binary.
Here, we will learn to read the text file in Python. Python takes the three required steps to read or write a text file.
Opening a Text FileTo open the text file in Python, we can use open() function. A file object is returned when open() function takes it as an argument. Code Output: This is line 1 This is line 2 This is line 3 This is line 4 The first argument is the file name, and the second argument is a mode of the file. Here r means read mode. Explanation: The open() takes mainly two arguments the filename and mode. It returns the file object, which is also called a handle. It can be used to perform various operations to the file. We can specify the mode of the file while opening a file. The mode of file can be read r, write w, and append a. We will open the text file using the open() function. Reading a Text FilePython provides the various function to read the file, but we will use the most common read() function. It takes an argument called size, which is nothing but a given number of characters to be read from the file. If the size is not specified, then it will read the entire file. Code Explanation: Here, all the information or contents in the file are stored in the read() function. Then we will print the contents. Closing a Text FileTo close the file, we can simply use close() function to terminate the file. Code Example Program:Code Output: This is line 1 This is line 2 This is line 3 This is line 4 Explanation: In the above code, we can see the read() function read the character according to its given size from the file. The con1 variable read the next 10 characters from the last read() function. In the last line, we closed the file after performing the read operation using the close() function. Next TopicHow to use for loop in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India