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.
Reading a Text FilePython provides a built-in function open() to open a file. It 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. Python 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. Example – Output: This is line 1 This is line 2 This is line 3 This is line 4 ExplanationIn 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. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263618.html