1

I have multiple text files in a folder where data is the form of- text file 1 and text file 2

I want to extract the file name and IOS value from text file 1 and file name and MB/s value from text file 2 and store it in excel file

here's my code-

import os

path = "Folder Path"
os.chdir(path)

def read_text_file(file_path):
    with open(file_path, 'r') as f:
        print(f.read())
  
for file in os.listdir():
    if file.endswith(".txt"):
        file_path = f"{path}\{file}"
  
        read_text_file(file_path)

with open ('text file 1.txt') as f:
for line in f:
    read = line.spilt(" ")
    print (IOS)

with open ('text file 2.txt') as f:
for line in f:
    read = line.spilt(" ")
    print (BW)MB/s
  

How do I solve this ?

sherkhan
  • 17
  • 3
  • The code you've presented contains many syntactical errors. You'll need to fix those. Then you need to decide on what the file format rules are. Is the filename the same as the first line within the file (minus the colon)? Is the IOS token always in the last line? Once you've thought that through it should be very straightforward –  Oct 20 '21 at 11:46
  • @BrutusForcus yes the filename is the same as the first line within the file and IOS and MB/s are not the last line of the text document, I cropped the rest of the data for convenience – sherkhan Oct 20 '21 at 11:54

1 Answers1

0

On the basis of what's been said in the comments, here's a way to search all of the text (.txt) files in a given folder for a pattern as defined in the regular expression in this code. The code will emit the IOS value and the name of the file in which it was found.

from glob import glob
import os
import re

FOLDER = 'foo' # the folder where the txt files can be found

for txt in glob(os.path.join(FOLDER, '*.txt')):
    with open(txt) as tfile:
        for line in tfile:
            if (m := re.match('.*IOS=(?P<IOS>.*),.*BW=(?P<BW>.*) ', line)):
                print(f'filename={txt}, IOS={m.group("IOS")} BW={m.group("BW")}')
                break