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
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
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.DIR.rglob("*.txt") for recursive searches.Troubleshooting notes:
OSError and are handled above.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 .
Jump to Post— TrustyTony 888What how have you tried to do it?
Post your code and we can see what is your problem
Tony
Jump to Post— jice 53import 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")])
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.
Don't know if Im supposed to link videos or not but its hard to explain. So here are a couple links to understand it clearly.
http://www.youtube.com/watch?v=0DHt_gC-k_E
http://www.youtube.com/watch?v=gNVlxvSEFO4
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 We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.