So, in the previous tutorial, we have created a file named 'myfirstfile.txt', with the below contents,
Now, let us see, how can we read the above file in Python.
We can use the 'read( )' Function to read the total file.
There is just one mode for reading a file :
myfile = open("myfirstfile.txt", "r") str = myfile.read() print(str) myfile.close()
We can use the 'readline( )' Function to read the first line of the file.
myfile = open("myfirstfile.txt", "r") str = myfile.readline() print(str) myfile.close()
So, in the above example, we have used the 'readline( )' Function to read the first line of the file.
Rest of the lines are just the same.
We can use the number of character with the 'read( )' Function to read the File by number of characters.
myfile = open("myfirstfile.txt", "r") str = myfile.read(9) print(str) myfile.close()
So, in the above example, we have used the 'read( )' Function and specified '9' as argument to read the first 9 characters of the file.
And got the below output.
In the above example, we have used the 'read( )' Function and specified '9' as argument to read the first 9 characters of the file.
Now, the file pointer should be at '9'.
And we can get the current file pointer using the 'tell( )' Function.
myfile = open("myfirstfile.txt", "r") str = myfile.read(9) print(myfile.tell()) myfile.close()
And all we have done is used the 'tell( )' Function to get the position of the file pointer.
And as we know the current file poin ter is at 9. So we got 9 as output.
In the above example, we have used the 'tell( )' Function to identify the current file pointer position.
Now, what if we want to change the file pointer, so that it points to some other location.
And we can achieve it using the 'seek( )' Function.
Let us see in the below example.
myfile = open("myfirstfile.txt", "r") str = myfile.read(9) print(myfile.tell()) myfile.seek(0) print(myfile.tell()) myfile.close()
So, if we see the output, we can see that the 'tell( )' Function is pointing to position 9.
Then we have used the 'seek( )' Function to reset the position of the pointer to '0'.
And if you see the next 'tell( )' Function,
It points to location '0'.