Pork Lord
Pork Lord

Reputation: 264

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

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

Upvotes: 0

Views: 418

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191743

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) 

Upvotes: 4

M B
M B

Reputation: 3430

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:

Upvotes: -1

Related Questions