0

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

4
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by pyTony
0

What how have you tried to do it?

Post your code and we can see what is your problem

Tony

Edited by pyTony: n/a

0

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

0
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")])

Edited by jice: n/a

0

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

Edited by pyTony: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.