In many programming languages, file handling is very important and it is done with different methods. In Python Programming, file handling is also done. To do this, we use python open function. Open() function takes two different parameters. One of them is file name and the other is the mode of the function. Here, we are talking about Python File Read. So, we will use “r” as the second parameter of open() function. In other words, to read a file in python, we use open() function with “r” parameter.
There are different modes of Python open() function. These modes are given below:
“r” mode, in other words, “read” mode is the default mode of python open() function. Here, we will focus on python file read.
Table of Contents
So, how can we use python open() function to open and read a file?
Think about that, we have a demo file in the same folder of python. The name of this file is filexyz.txt. This file will include a text in two lines inside like below:
Below you can find an example syntax to read a file.
In this example, we have also used read() method of python file object. The return of this Python File Read code will be the content of the demo file, filzexyz.txt.
By default, the return of this code will be with the whole content of the file. But what if we use an extra parameter inside python read() method? If we use an extra parameter as a nubmer in read() method, this means that print only the characters up to that number. Let’s show this, with the same example.
If we use, 5 as a parameter of read() method like below;
we will return only the characters up to index five. This means that only the characters in the index 0,1,2,3 and 4 will be showed.
In another example, we will read 10 characters like below:
The output of this Python File Read code will be:
We can also do this read with lines only. For example, we can read only the first line or we can read first two lines. TO do this, we will use python readline() method.
If we use readline() method one time, it will give the first line in the demo file. If we use it two times, it will give also the second line. And so on.
In the below example, first, we read only the first line of the demo file. Again, think about the demo file, filexyz.txt is in the same directory with python.
The output will be the first line of the demo file like below:
If we use readfile() method two times in the code, we can read two lines. In the below example, we will read two lines of the demo file.
The output will be:
In the above examples, we have opened files and read them. As a good programming habbit, after opening the files, it is good to close these files. To do this, we will use python close() method.
We can close our demo file like below:
Yes, we have learned Python File Read mechanism. In other words how to read a file in Python. You will use this method too much in your coding activities. So, these methods are very important for you.
Leave a Reply