Python read file
Python read file allows us to read contents of file in very easy way. If we want to read some contents to file, first of all we need to open a file and create object of that file. With that object we can read() a file.
In our previous article have discussed about file handling and its various methods . If you want to learn it then you can visit link below:
Now we will discuss about various other operations on files like reading , renaming a file etc. Let’s talk about reading a file.
Python read file ( read() )
Python allows us to read contents of file in very easy way. If we want to read some contents to file, first of all we need to open a file and create object of that file. With that object we can read() a file. We can read:
- According to size
- Whole file.
Python read file : According to size (particular contents)
We can read particular content of file by passing size as its argument. The size is in number of bytes we want to read from a file. In this, pointer’s first location is on the beginning of file and last location points to the size given (bytes).
objname.read([size in bytes ])
Python read file : Entire file
If we does not specify size to read() then it will read all the contents of the file till end. In this, pointer’s first location is on the beginning of file and last location points the last element of file.
As you can see in the example above, In line 2-5, i have read only 10 bytes (characters including spaces) , so it prints “I can delete” as output . And in line 8-12 , i have read entire file without specifying size (bytes) to read.
Python read file : Read line ( readline() )
You can read single line of the file by calling readline() method. If you want to read more than one line, you can use readline() method number of times , you want to read lines.
For example , if you want to read first two lines from a file, then you can do so by calling readline() function two times.
Python read file :Looping through lines
To read a file, we can also put loop through all the elements of file and print on console. Here is the code for looping through elements of file .
Python close() method
You may see in our previous article, i used close() method there. So what close() is?
We use close() method to close particular file object, or opened file. Once close() method is executed, we can’t further write or read particular file object. Python automatically closes a file, once we create the other object (instance) of same file. After closing file object, if we try to read/write that object, it returns error.
As you can see, in example above, i am trying to write contents on file , after closing it. So it cause to return an error i.e.
ValueError: I/O operation on closed file.
If you want to learn more about file handling , deleting , renaming files than you can visit the link below:
So it is all about Python read file. We will discuss some more methods of Python file handling . i hope you guys enoyed it, thanks!!!