函数在python中返回master的位置。
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
我想得到结果“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
但是,如何使用以下代码实现上述功能?如何修改?
def find(path):
return [os.path.join(root,fn)
for root,dir,files in os.walk(dirs)
for fn in files]
答案 0 :(得分:5)
返回路径的列表,而不仅仅是单个路径:
def find(path):
return [os.path.join(root, fn)
for root, dirs, files in os.walk(path)
for fn in files]
您也可以在内部循环中使用yield
来获取生成器函数,请参阅The Python yield keyword explained。
答案 1 :(得分:1)
你想要的是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
答案 2 :(得分:0)
如果只需要列出的/ home / bb / C目录,可以使用以下三种方法
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/*')