Reading files







Hello Folks....!!!

Today we are going to see how to read a file in python.

read( ) method in Python

The file must be first opened in read mode. To know how to open a file in read mode, refer this link. read() is a built-in method in python, which provides facilities to read either specified number of bytes or up to the end of the file. The syntax is as follows:

file_object.read(size)

Here if the size is mentioned, it reads the specified number of bytes, otherwise the whole file is read. Let us look at an example.

Let us consider a text file sample_file.txt. It has few lines on Python. I have given the snap shot of the file I used below.




Now let us open and read its contents into a string data structure. You can read it into any data structure of your choice. Let us read first ten bytes. So we pass the parameter 10. 




Note that a blank space will also be considered as a byte, To explain the output got I am denoting the spaces with an underscore (_). The output is Python_is_. If you count with the underscores, then you will get 10 bytes long string. If you don't pass any parameter for the method and simply write f.read(), the you will get the output below.





Now if you use read (10), the first 10 bytes will be rad and the file pointer will be placed after the 10th byte. Now if use an another read (10), before closing the file, then you will get next 10 bytes. For example look at the code below.


tell() and seek() operations

If you want to know where the cursor (file pointer) is currently placed you can use file_object.tell(). It will return at what number of byte the cursor is. To reposition the cursor, you can use file_object.seek(byte_number). This will place the cursor in the specified byte number. Let us look at an example.





Next Topic👉

Comments