Skip to content

How to Read a File in Python

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
Code language: plaintext (plaintext)

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())
Code language: Python (python)

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())
Code language: Python (python)

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))
Code language: PHP (php)

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())
Code language: Python (python)

If you called this twice, then it would read the first two lines:

f = open("somefile.txt", "r") print(f.readline()) print(f.readline())
Code language: Python (python)

A better way to do this, is to loop through the file:

f = open("somefile.txt", "r") for x in f: print(x)
Code language: Python (python)

How to Close a File in Python

It is always good practice to close a file after you have opened it.

See also  HP Pavilion Laptop Madness

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()
Code language: Python (python)

Tags:
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Software House
13 days ago

great info, luckily I find your website, now I am going to bookmark this sites

1
0
Would love your thoughts, please comment.x
()
x