Python Read Files

Python Read Files

Once a file is successfully opened using the open() function, you can read its contents. Python provides multiple methods to extract the data exactly how you need it.

Assume we have a file named demofile.txt located in the same folder as Python, containing the following text:

Hello! Welcome to demofile.txt This file is for testing purposes. Good Luck!


1. Read the Whole File

The read() method reads the entire content of the file and returns it as a single string.

f = open("demofile.txt", "r")
print(f.read())

Read Only Parts of the File

By default, the read() method returns the whole text, but you can also specify how many characters you want to return.

# Return only the first 5 characters
f = open("demofile.txt", "r")
print(f.read(5)) 

2. Read Lines

You can return one line at a time by using the readline() method.

f = open("demofile.txt", "r")
print(f.readline()) # Reads the first line
print(f.readline()) # Reads the second line

If you want to read all the lines and store them as a list where each line is an item, use readlines():

f = open("demofile.txt", "r")
lines_list = f.readlines()
print(lines_list[0])

3. Looping Through a File

By looping through the lines of the file, you can read the whole file line by line. This is incredibly memory-efficient for very large files, because it doesn't load the entire file into memory at once.

f = open("demofile.txt", "r")
for x in f:
  print(x)

4. Close Files

It is considered good practice to always close the file when you are done with it. Unclosed files can cause memory leaks and unpredictable behavior in your applications.

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Pro Tip: Modern Python code often uses the with statement when opening files. The with statement automatically takes care of closing the file for you, even if an error occurs while processing it!

with open("demofile.txt", "r") as f:
    print(f.read())
# The file is now safely closed automatically.

Exercise

?

Which method returns a list of all lines in the file?