listdir

Chris Angelico rosuav at gmail.com
Mon Sep 5 12:39:46 EDT 2016


On Tue, Sep 6, 2016 at 2:29 AM, Smith <smith at smith.it> wrote:
>> What exactly are you expecting the 'break' to do here? Can you explain
>> to me the intent of your code?
>>
>> ChrisA
>>
> I'd like to create a script that searches the directory .py files.
> If the script does not find the file extension .py would return the error
> message "File Not Found".

Okay. So the logic needs to be like this:

For every file in this directory:
    If the file has the extension ".py":
        Print out the file name
If we didn't print out any file names:
    Print out "File not found"

Notice how this pseudo-code is extremely close to actual Python code.
Here's a revision of your code that does more-or-less that. (I'm
keeping your original prompt; Python 3 is quite happy to work with all
human languages equally, and not just as text strings - you can name
your variables in Italian, too.)


a = input("Digita la directory dove vuoi trovare i file py:  ")
found_any = False
for file in os.listdir(a):
    if file.endswith(".py"):
        print(file)
        found_any = True
if not found_any:
    print("File not found")

There's no "else" clause, because the algorithm doesn't care about
non-py files; it cares only whether or not any .py files were found.

Does that help you understand what's going on? I can elaborate more if you like.

ChrisA



More information about the Python-list mailing list