Python Learning (Part 6)
In this article we will get to know how to read files in Python.
Firstly we need to create a new python file where data is available as shown below
The TestFile is the python file with data as “One”, “Two” and “Three”.
Open and Read the File:
Now we will open this Text file (TestFile) in Python file (Actual File) as shown below
Above the open() function is used to open the file, “r” indicates read only mode.
Output:
As you can see above in the output after a data, a blank/extra line is displayed and after that blank/extra line another data is getting displayed.
To solve this blank/extra line issue we have to use “end” in print function as shown below
Output:
We can now see the data one after the other.
We have used for loop to get the data of Text file(TestFile) into Python File(Actual File), also we can use read() method to get the data as shown below
Output:
Read Only Parts of the file :
Get Arjun Sharma’s stories in your inbox
Join Medium for free to get updates from this writer.
The read() method by default return the whole text, but you can also specify how many characters you want to return as shown below
By using the above code we should get first five characters from Text File(TestFile) in the results.
Output:
As we can see instead of 5 it has shown 4 characters in the results.
3 characters on data “One”, 4th character is nothing but the line which is separated between data “One” and “Two” and finally 5th character is “T”.
Read Lines :
By using readline() method you can return first line as shown below
Output:
Now by calling readline() method two times, first 2 lines will get displayed as shown below
Output:
Down see 60 mins video to learn Python: -







