1,105,334 Community Members

Reading two first line of the txt file?HOW?

Member Avatar
tony75
Posting Whiz in Training
267 posts since Mar 2011
Reputation Points: 10 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 0 [?]
 
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

Member Avatar
pyTony
pyMod
6,103 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 

What how have you tried to do it?

Post your code and we can see what is your problem

Tony

Member Avatar
tony75
Posting Whiz in Training
267 posts since Mar 2011
Reputation Points: 10 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
South
Newbie Poster
5 posts since Apr 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
jice
Posting Whiz in Training
225 posts since Oct 2007
Reputation Points: 53 [?]
Q&As Helped to Solve: 57 [?]
Skill Endorsements: 1 [?]
 
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")])
Member Avatar
pyTony
pyMod
6,103 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
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
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: