python,返回位置和文件大小

标签 python return

函数返回 master well 在 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

三个位置“返回”不是我想要的。

我想得到结果“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]

最佳答案

返回路径的列表,而不仅仅是单个路径:

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 .

关于python,返回位置和文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9953355/

相关文章:

C++ 通过引用返回和通过常量引用返回值被复制

Java传入字符串并返回字符串

python - 如何在 PyParsing 中构造一个相当于 FollowedBy 子类的 "leading"

python - 并行 python 还是 MPI?

Python:避免关于太多参数的 Pylint 警告

c# - 在方法中抛出异常会导致方法返回吗?

function - 如何在Lua中检索表中的另一个变量?

Python "Segmentation fault: 11"运行时 "import cv"或 "import cv2"

python - 使用子图旋转 x 刻度标签

php - 在 php 中, "return false"在 echo 语句之后有什么作用吗?