Question : Select text from files and create new file

Hello,
I have several text files in the same directory that I would like to extract two lines of text (first and last) and insert them all into one new text file. Divided by something like #################

For example in the text file I attached I would want these two lines extracted:

 2016_5class_small_P1_vs_P2
 smaller or equal delta = 0.01514132981509637

for a result in the new text file like:

 2016_5class_small_P1_vs_P2
 smaller or equal delta = 0.01514132981509637
#############################

Thank you, I appreciate annotated text so I can learn whats going on.
JE

Answer : Select text from files and create new file

Try the sample below. Modify the path as needed. Modify the output file name as needed. Feel free to ask.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
import os
path = r'.'
       # r'C:\Documents and Settings\u4cncmgj\Desktop\STAT_R_EUA\results2\residtext'
 
def extractInfo(fname, fout):
    idExtracted = False  # indication of not extracted first non-separator line
    lastline = ''        # init
    f = open(fname)
    for line in f:
        line = line.lstrip()  # strip the left whitespaces
        if line == '' or line.startswith('==='):
            continue          # skip the initial non-info lines
        
        if not idExtracted:
            fout.write(line)       # extract the first info line    
            idExtracted = True     # indicate that it was done
 
        lastline = line            # remember the last non-empty
 
    f.close() 
    fout.write(lastline)           # extract the last line
    fout.write('\n#################\n')
 
 
fout = open('output.txt', 'w') 
for barename in os.listdir(path):
    name = os.path.join(path, barename)
    if not os.path.isdir(name):
        extractInfo(name, fout)
fout.close()
Open in New Window Select All
Random Solutions  
 
programming4us programming4us