Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python os.walk returns nothing

Tags:

python

I have a problem with using os.walk on Mac. If I call it from python terminal, it works perfect, but if I call it via a python script, it returns empty list. For example:

    import os

    path = "/Users/temp/Desktop/test/"
    for _ ,_ , files in os.walk(path):
        test = [my_file for my_file in files]

    print test

then, it prints:

    []

and I am pretty sure that the path does exists. Any idea what is the problem?

like image 965
user2308191 Avatar asked Sep 03 '26 12:09

user2308191


1 Answers

You most likely need to intantiate the test list outside the for loop, for this to work.

import os

path = "/Users/temp/Desktop/test/"
test = []
for _ ,_ , files in os.walk(path):
    test.extend([my_file for my_file in files])

print test
like image 183
miah Avatar answered Sep 05 '26 03:09

miah