Iterate a directory for all files with file extension '.py'

Question:

I am attempting to find every file in a directory that contains the file extension: ‘.py’

I tried doing:

if str(file.contains('.py')):
    pass

I also thought of doing a for loop and going through each character in the filename but thought better of it, thinking that it would be too intense, and concluded that there would be an easier way to do things.

Below is an example of what I would want my code to look like, obviously replacing line 4 with an appropriate answer.

def find_py_in_dir():
    for file in os.listdir():
        #This next line is me guessing at some method
        if str(file.contains('.py')):
            pass
Asked By: Pork Lord

||

Answers:

if requires a boolean and not a string, so remove the str and replace .contains with .__contains__

if file.__contains__ ('.py'):

You can also do:

if '.py' in file:
Answered By: M B

Ideally, you’d use endswith('.py') for actual file extensions, not checking substrings (which you’d do using in statements)

But, forget the if statement

https://docs.python.org/3/library/glob.html

import glob 
for pyile in glob.glob('*.py'):
    print(pyile) 
Answered By: OneCricketeer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.