Home > Net >  Loop to run directory of .txt files
Loop to run directory of .txt files

Time:03-15

I want to write a code that runs each .txt file in a large directory containing text files. I want to print every single occurrence of the context (i.e. line) in which the input word appears in, as well as the title of the document(s).

Let's say the word 'cat' appears in 5/10 documents. I want to print every single sentence in which 'cat' appears in.

Here's the code I have so far. It does "work", but it only prints the occurrence of the input word in one document, not in every single document.

Thank you!

import os
import re


dir1=("/my directory/")

for txt in os.listdir(dir1):
    with open (dir1 "/" txt, "r", encoding="utf8") as f_obj:
        contents=f_obj.readlines()
        word=input("Type the word whose context you want to find:")
        for line in contents:
            if re.search(word,line):
                print("Title of document:", f_obj.name)
                print("Context of use:", line)    

CodePudding user response:

You could move the declaration of the input word outside of the for-loop, like this:

import os
import re


dir1=("/my directory/")

word=input("Type the word whose context you want to find:")

for txt in os.listdir(dir1):
    with open (dir1 "/" txt, "r", encoding="utf8") as f_obj:
        contents=f_obj.readlines()
        for line in contents:
            if re.search(word,line):
                print("Title of document:", f_obj.name)
                print("Context of use:", line)    

Now the same input word will be used for each of the documents. See below for example output with this change applied (and detecting cat across my two text files "t.txt" and "3.txt")

Type the word whose context you want to find:cat
Title of document: /my directory/t.txt
Context of use: cat on a bat

Title of document: /my directory/t.txt
Context of use: bat on a cat

Title of document: /my directory/3.txt
Context of use: cat on a bat

Title of document: /my directory/3.txt
Context of use: cat on a mat

  • Related