Home >>Python Tutorial >Python Read File
This is the python read file module of the python tutorial. And to understand the concepts in this module you need to first assume that you have a particular file. And that particular file in located in the similar folder where python is located. Imagine that the file looks something like what is illustrated below.
Hello! Welcome to demofile.txt This file is for treating purposes. Good Luck!
If you wish to open this particular python read file then you would have to use the open ( ) function. This is a built-in function. And as we have mentioned before, this function helps in returning the object of the file. You can also use the read ( ) method to read all the content of that particular file. For example
f = open (“demofile.txt”, “r”) print (f.read ( ) )
You must now know that the read ( ) method returns the entire python readline text by default. But you can also choose to read only some specific parts of the entire text and this you can do by specifying the total number of characters that you want the file to return. If you wish that the file would return only the first five characters then the python readline example for that is mentioned below.
f = open (“demofile.txt”, “r”) print (f.read ( 5 ) )
If you wish to return a single python readline then you can do that by using the readline ( ) method. For example,
f = open (“demofile.txt”, “r”) print (f.readline ( ) )
If you wish to read two lines of the file then you can do that by using the readline ( ) method for two consecutive times. The python readline example is mentioned below.
f = open (“demofile.txt”, “r”) print (f.readline ( ) ) print (f.readline ( ) )
If you wish to read the entire file line by line then you can also do that in this programming language. And to do that you will be required to loop through the file. And the example for python read text file is mentioned below.
f = open (“demofile.txt”, “r”) for x in f : print ( x )
With this, we finish the Python read text file part of our entire python tutorial.