How to Read First N Lines of a File in Python?

5/5 - (3 votes)

Problem Formulation

Given a filename and an integer n.

How to read the first n lines of the file in your Python script?

Here’s an overview of the solutions:

How to Read First N Lines of a File in Python?

Method 1: Store Head in a List of Strings

To read the first n lines of a given file and store each line in a list of strings, you can use list comprehension expression [next(file) for x in range(n)].

  • The expression next(file) gets the next line of the file.
  • The context for x in range(n) repeats this n times.

Here’s a code script in a file '' that reads the first n=4 lines of itself:

n = 4
filename = ''

with open(filename) as my_file:
    head = [next(my_file) for x in range(n)]

The output is:

['n = 4\n', "filename = ''\n", '\n', 'with open(filename) as my_file:\n']

Method 2: Store Head in a String

You can also store the first n lines of a file in a single string using the following idea:

  • Create an empty string variable head = ''
  • Open the file with open(filename)
  • Iterate n times using a for loop
  • Appending the next line in the file to the end of the string head using string concatenation.

Here’s the specific code:

n = 4
filename = ''

head = ''
with open(filename) as my_file:
    for x in range(n):
        head += next(my_file)

The print() function gives the following output:

n = 4
filename = ''
head = ''

Method 3: Slicing and readlines()

If performance is not an issue for you, you can read the whole file using the readlines() function and then use slicing to access only the first n lines. For example, file.readlines()[:n] would return a list of the n first lines in the file.

n = 4
filename = ''

with open(filename) as file:
    head = file.readlines()[:n]

The output of this code snippet is:

['n = 4\n', "filename = ''\n", '\n', 'with open(filename) as file:\n']

This is not a very performant way to read the head of a file because you first read the whole file before throwing away everything but the first n lines. Thus, you should only use it if the files are relatively small and you don’t care too much about performance.

To learn everything you need to know about slicing, check out my book “Coffee Break Python Slicing”—bundled with my popular “Coffee Break Python” book here for a reasonable price. πŸ™‚

Method 4: Pandas

A simple and straightforward solution that doesn’t require explicit file I/O is provided by the pandas library. To read the first n lines of a file, you can use the pandas call pd.read_csv(filename, nrows=n).

For example, to read the first five lines of the file 'file.csv', the following two-liner will do:

import pandas as pd
head = pd.read_csv('file.csv', nrows=5)

You can check out my book “Coffee Break Pandas” to become a pandas expert using a fun puzzle-based learning approach.

🌍 Recommended Tutorial: How to Read the First Line of a File in Python?

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

πŸš€ If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skillsβ€”even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar β€œHow to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, tooβ€”from the comfort of your own home.

Join the free webinar now!