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:
Hello, this is a test file
With some contents
How to Open a File and Read it in Python
We can read
the contents of this file as follows:
f = open("somefile.txt", "r")
print(f.read())
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:
f = open("/some/location/somefile.txt", "r")
print(f.read())
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.
f = open("somefile.txt", "r")
print(f.read(5))
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 readline()
function:
f = open("somefile.txt", "r")
print(f.readline())
If you called this twice, then it would read the first two lines:
f = open("somefile.txt", "r")
print(f.readline())
print(f.readline())
A better way to do this, is to loop through the file:
f = open("somefile.txt", "r")
for x in f:
print(x)
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.
f = open("somefile.txt", "r")
print(f.readline())
f.close()