简体   繁体   中英

Python defining function outputs only first dir

when i def a function and try to use os.walk in it , the output is just the first file in the directory , i want to print out all there is in the C Drive.

#os.chdir=("..")
def dirslist():
 for root, dirs, files in os.walk("c://", topdown=False):
  for name in files:
    return(os.path.join(root, name))
  for name in dirs:
    return(os.path.join(root, name))

 print(dirslist())
def dirslist():

 answer = []
 for root, dirs, files in os.walk("c://", topdown=False):
  for name in files:
    answer.append(os.path.join(root, name))

  for name in dirs:
    answer.append(os.path.join(root, name))

 return answer

 print(dirslist())

return returns in the first iteration itself. What you want is to get paths from all iterations. One way is to change return to yield . Now dirslist becomes a generator function and yields your paths one by one.

def dirslist():
    for root, dirs, files in os.walk("c://", topdown=False):
        for name in files:
            yield(os.path.join(root, name))
        for name in dirs:
            yield(os.path.join(root, name))


print(list(dirslist()))

An alternate approach, if you're not a generator person, is to accumulate your paths in a list and return that instead.

def dirslist():
    paths = []
    for root, dirs, files in os.walk("c://", topdown=False):
        for name in files:
            paths.append(os.path.join(root, name))
        for name in dirs:
            paths.append(os.path.join(root, name))

    return paths

print(dirslist())

The main thing to note here is that return returns from a function only once, while yield returns at each iteration, resuming from immediately after the previous iteration each time it is invoked.

If you want to print out all there is in the C Drive. use print instead of return

Using return statements automatically ends a function. If you are going to use return, then know that your code is ending there. If you want to print it all, then concatenate all the strings and then do it all at the end in one return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM