Hi
I have a folder and its contain 5 text files.
My question is
How can I navigate to folder and read two first line of the txt files in folder with python scripts?

I will be very greatful for your help.

Reagards
Tony

Dani AI

Generated

A concise, modern, memory-efficient Python 3 pattern for the original question from : read the first two lines of every .txt file in a folder, print a filename header, and handle common pitfalls (encoding, missing lines, permission errors). This complements the answers from and by avoiding loading whole files into memory and by adding clearer file-level reporting.

from pathlib import Path
from itertools import islice

DIR = Path(r"C:\path\to\the\dir")  # use Path('.') for current directory

for path in sorted(DIR.glob("*.txt")):
    if not path.is_file():
        continue
    print(f"--- {path.name} ---")
    try:
        with path.open("r", encoding="utf-8", errors="replace") as fh:
            for line in islice(fh, 2):
                print(line.rstrip("\r\n"))
    except OSError as exc:
        print(f"(could not open {path.name}: {exc})")

Why this approach:

  • islice(fh, 2) reads only the first two lines without loading the whole file into memory (safer for large files).
  • path.open(..., errors="replace") avoids crashes on unexpected byte sequences; change the encoding if files use a legacy Windows code page.
  • sorted(...) makes file processing deterministic; replace the key with p.stat().st_mtime to sort by modification time.
  • Use DIR.rglob("*.txt") for recursive searches.

Troubleshooting notes:

  • Files with fewer than two lines will print whatever exists; no exception is raised.
  • Permission errors or locked files surface as OSError and are handled above.
  • For environments still on Python 2 (EOL since 2020), use codecs.open() or upgrade to Python 3 for better Unicode handling.

This solution keeps the clarity of 's filename-aware output while improving memory behavior compared with the one-liner shown by .

Recommended Answers

All 5 Replies

What how have you tried to do it?

Post your code and we can see what is your problem

Tony

Reading just two first line on the each text files in the folder.

import glob
print "\n\n".join(["".join([l for l in open(inf).readlines()[:2]]) for inf in glob.glob("C:\\path\\to\\the\\dir\\*.txt")])

Ok, another alternative solution:

from __future__ import print_function

import os


PATH = os.curdir
EXTENSIONS = '.TXT','.ME','1ST'

for filename in (inf for inf in os.listdir(PATH) 
                  if inf.upper().endswith(EXTENSIONS)):
     with open(filename) as textfile:
          try:
              print(next(textfile), next(textfile))
              print('-'*40)
          except StopIteration:
                 continue
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.