Home > Software engineering >  Python: Finding files in directory but ignoring folders and their contents
Python: Finding files in directory but ignoring folders and their contents

Time:04-22

So my program search_file.py is trying to look for .log files in the directory it is currently placed in. I used the following code to do so:

import os

# This is to get the directory that the program is currently running in
dir_path = os.path.dirname(os.path.realpath(__file__))

# for loop is meant to scan through the current directory the program is in
for root, dirs, files in os.walk(dir_path):
    for file in files:
        # Check if file ends with .log, if so print file name
        if file.endswith('.log')
            print(file)

My current directory is as follows:

search_file.py

sample_1.log

sample_2.log

extra_file (this is a folder)

And within the extra_file folder we have:

extra_sample_1.log

extra_sample_2.log

Now, when the program runs and prints the files out it also takes into account the .log files in the extra_file folder. But I do not want this. I only want it to print out sample_1.log and sample_2.log. How would I approach this?

CodePudding user response:

Try this:

import os

files = os.listdir()

for file in files:
    if file.endswith('.log'):
        print(file)

The problem in your code is os.walk traverses the whole directory tree and not just your current directory. os.listdir returns a list of all filenames in a directory with the default being your current directory which is what you are looking for.

os.walk documentation

os.listdir documentation

CodePudding user response:

By default, os.walk does a root-first traversal of the tree, so you know the first emitted data is the good stuff. So, just ask for the first one. And since you don't really care about root or dirs, use _ as the "don't care" variable name

# get root files list.
_, _, files = next(os.walk(dir_path))
for file in files:
    # Check if file ends with .log, if so print file name
    if file.endswith('.log')
        print(file)

Its also common to use glob:

from glob import glob
dir_path = os.path.dirname(os.path.realpath(__file__))
for file in glob(os.path.join(dir_path, "*.log")):
    print(file)

This runs the risk that there is a directory that ends in ".log", so you could also add a testing using os.path.isfile(file).

  • Related