0

I am trying to get only numbers from a particular row from 10 different text files. As an output, I want those numbers appended as a list. I'm a new learner. I would appreciate your help. tried this one but not working

import os
import sys,re
line_number=69 
path = r'C:\Users\arpan\OneDrive\Desktop\New folder' 

for filename in os.listdir(path):
   with open(os.path.join(path, filename), 'r') as f: 
       #print (filename)
       file = open(filename)
       all_lines_variable = file.readlines()
       sys.stdout = open("output", "a")    #print output file
       print(filename, all_lines_variable[line_number])
sys.stdout.close()

1 Answers1

0

You can try this script, it will extract from all files line number 69 and then appends it to output.txt file:

import os
import re

line_number=69
path = r'C:\Users\arpan\OneDrive\Desktop\New folder'

with open('output.txt', 'w') as f_out:
    for file in os.listdir(path):
        with open(os.path.join(path, file), 'r') as f_in:
            lines = f_in.readlines()
            print(' '.join(re.findall(r'\d+', lines[line_number])), file=f_out)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91