Better way to find absolute paths during os.walk()?

前端 未结 3 456
半阙折子戏
半阙折子戏 2021-01-14 02:51

I am practicing with the os module and more specifically os.walk(). I am wondering if there is an easier/more efficient way to find the actual path

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-14 03:49

    Your work around should work fine, but a simpler way to do this would be:

    import os
    
    threshold_size = 500
    
    root = os.getcwd()
    root = os.path.abspath(root) # redunant with os.getcwd(), maybe needed otherwise
    for folder, subfolders, files in os.walk(root):
        for file in files:
            filePath = os.path.join(folder, file)
            if os.path.getsize(filePath) >= threshold_size:
                print filePath, str(os.path.getsize(filePath))+"kB"
    

    The basic idea here is that folder will be an absolute normalized path if the argument to os.walk is one and os.path.join will produce an absolute normalized path if any of the arguments is an absolute path and all the following arguments are normalized.

    The reason why os.path.abspath(file) doesn't work in your first example is that file is a bare filename like quiz.py. So when you use abspath it does essentially the same thing os.path.join(os.getcwd(), file) would do.

提交回复
热议问题