Thursday, March 5, 2015

Find all .txt files

In this post, you are going to see how to find all .txt files in your computer using python's os module.


You can see the code below:




import os

def find_all_txtfiles():

    for root, dirs, files in os.walk("/"):
        for file in files:
            if file.endswith(".txt"):
                 print(os.path.join(file))

find_all_txtfiles()



As you can see it's pretty easy to use this code, in order to find whatever kind of file you 
want. You only have to change .txt extension .

Also, you can narrow your search to a specific directory by adding the path of the 
directory, that you would like to search.( for root, dirs, files in os.walk("/home/user/Desktop/python") ).



No comments:

Post a Comment