2

Functions return the position of master well in python.

def myPath():
    for root,dirs,files in os.walk(dir):
        for fn in files:
            path = os.path.join(root, fn)
            return path
        return path
    return path
ls /home/bb/C/
a.out  main.c  simple_write  t.c

Three positions "return" is not what I want.

I want to get result "All the files in the C"

def filesize(path):
    for root, dirs, files in os.walk(PATH):
        for fn in files:
            path = os.path.join(root, fn)
            size = os.stat(path).st_size
            yield size,path

for size,path in filesize(PATH):
        print size,path

but,How to achieve the above functions with the following code? How to modify it?


def find(path):
    return [os.path.join(root,fn)
        for root,dir,files in os.walk(dirs)
        for fn in files]
Community
  • 1
  • 1

3 Answers3

5

Return a list of the paths, not only a single path:

def find(path):
    return [os.path.join(root, fn)
            for root, dirs, files in os.walk(path)
            for fn in files]

You could also use yield inside the inner loop to get a generator function, see The Python yield keyword explained.

Community
  • 1
  • 1
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1

What you want is a generator:

def myPath(mydir):
    for root,dirs,files in os.walk(mydir):
        for fn in files:
            path = os.path.join(root, fn)
            yield path # <----- Instead of return


for path in myPath(some_dir):
    print path
bereal
  • 32,519
  • 6
  • 58
  • 104
0

Here are 3 ways if you need just the /home/bb/C directory listed

import os, glob

def listWithoutDirectories(path):
    return [os.path.join(root,fn)
        for root,dirs,files in os.walk(mydir)
            if(root==path)
                for fn in files]

def listWithDirectories(path)
    return [os.path.join(path,fn)
        for fn in os.listdir(path)]


print listWithoutDirectories('/home/bb/C')
print listWithDirectories('/home/bb/C')
#Or with a glob
print glob.glob('/home/bb/C/*')
Cadoo
  • 807
  • 5
  • 13