Search a String Inside a File in Python

0

In this Python project, we will create a python project that will look inside files for a string. It will search files for a particular string.

we will use the python os module to work with the operating system-related tasks. This is actually a cool project that you should have in your pocket.

search for a text in a file

Search a String Text inside a file in Python

Run the following code in your code editor and pass the string and path of the file. It will be able to search all files and tell you if a string is available or not.


import os

text = input("input text : ")

path = input("path : ")

# os.chdir(path)


def getfiles(path):
    f = 0
    os.chdir(path)
    files = os.listdir()
    # print(files)
    for file_name in files:
        abs_path = os.path.abspath(file_name)
        if os.path.isdir(abs_path):
            getfiles(abs_path)
        if os.path.isfile(abs_path):
            f = open(file_name, "r")
            if text in f.read():
                f = 1
                print(text + " found in ")
                final_path = os.path.abspath(file_name)
                print(final_path)
                return True

    if f == 1:
        print(text + " not found! ")
        return False


getfiles(path)

You may also like to read

Summary and Conclusion

you have seen how you can create a python program that can search all over the file for a particular text. You can build other python projects as well. This is it for this tutorial. If you have any questions please leave them in the comment section.

Post a Comment

0Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !