Back to blog
Sep 01, 2025
3 min read

Tenth Line

Given a text file file.txt, print just the 10th line of the file.

Difficulty: Easy | Acceptance: 36.70% | Paid: No Topics: Shell

Given a text file file.txt, print just the 10th line of the file.

Examples

Assume that file.txt has the following content:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Line 11
Line 12
Line 13
Line 14
Line 15

Your script should output the tenth line:

Line 10

Constraints

- 0 <= N (number of lines in the file) <= 1000
- The file is named file.txt and is located in the current directory.

Approach 1: Iterative Line Reading

Intuition The most memory-efficient way to solve this problem is to read the file line by line. We maintain a counter to track the current line number. Once the counter reaches 10, we print that line and immediately stop processing the file. This avoids loading the entire file into memory.

Steps

  • Open the file file.txt for reading.
  • Initialize a counter to 0.
  • Loop through the file one line at a time:
    • Increment the counter.
    • If the counter equals 10, print the current line and exit the loop.
  • Close the file (handled automatically in some languages via context managers or destructors).
python
with open('file.txt', 'r') as f:
    for i, line in enumerate(f):
        if i == 9:
            print(line, end='')
            break

Complexity

  • Time: O(n), where n is the number of lines. In the worst case, we read the whole file.
  • Space: O(1), we only store the current line and a counter.
  • Notes: This is the optimal approach for very large files as it uses constant memory.

Approach 2: Read All Lines

Intuition If the file size is small (as per the constraints), we can simplify the code by reading the entire file into memory at once. We split the content into an array of lines and directly access the element at index 9 (the 10th line).

Steps

  • Read the entire content of file.txt.
  • Split the content into a list or array of lines.
  • Check if the list has at least 10 elements.
  • If yes, print the element at index 9.
python
with open('file.txt', 'r') as f:
    lines = f.readlines()
    if len(lines) &gt;= 10:
        print(lines[9], end='')

Complexity

  • Time: O(n), to read the file and split it into lines.
  • Space: O(n), to store all lines in memory.
  • Notes: This approach is concise and easy to write but less memory-efficient for very large files compared to Approach 1.