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 ?

2
  • 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 Commented Oct 20, 2021 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 Commented Oct 20, 2021 at 11:54

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

I need IOS value only for text file 1, and MB/s value for text file 2 ....can you suggest me how can i do it
It's not all the homework, i'm just asking for help in extracting that MB/s value...
I've enhanced the RE in my code. Maybe that will help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.