If you need to read a file in Python, then you can use the
open() built-in function to help you.
Let’s say that you have a file called
somefile.txt with the following contents:
How to Open a File and Read it in Python
read the contents of this file as follows:
This will print out the contents of the file.
If the file is in a different location, then we would specify the location as well:
How to Only Read Parts of a File in Python
If you don’t want to read and print out the whole file using Python, then you can specify the exact location that you do want.
This will specify how many characters you want to return from the file.
How to Read Lines from a File in Python
If you need to read each line of a file in Python, then you can use the
If you called this twice, then it would read the first two lines:
A better way to do this, is to loop through the file:
How to Close a File in Python
It is always good practice to
close a file after you have opened it.
This is because the
open() method, will keep a file handler pointer open to that file, until it is closed.