Home > front end >  Iterate a directory for all files with file extension '.py'
Iterate a directory for all files with file extension '.py'

Time:07-24

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

CodePudding user response:

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) 

CodePudding user response:

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:
  • Related