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

前端 未结 3 457
半阙折子戏
半阙折子戏 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:34

    I think there you mistook what abspath does. abspath just convert a relative path to a complete absolute filename.

    For e.g.

    os.path.abspath(os.path.join(r"c:\users\anonymous\", ".."))
    #produces this output : c:\users
    

    Without any other information, abspath can only form an absolute path from the only directory it can know about, for your case the current working directory. So currently what it is doing is it joins os.getcwd() and your file

    So what you would have to do is:

    for folder, subfolders, files in os.walk(os.getcwd()):
        for file in files:
            filePath = os.path.join(os.path.abspath(folder), file)
    
    0 讨论(0)
  • 2021-01-14 03:37

    This simple example should do the trick. I have stored the result in a list, because for me it's quite handy to pass the list to a different function and execute different operations on a list.

    import os
    directory = os.getcwd()
    list1 = []
    
    for root, subfolders, files in os.walk(directory):
      list1.append( [ os.path.join(os.path.abspath(root), elem) for elem in files if elem ])
    # clean the list from empty elements
    final_list = [ x for x in list1 if x != [] ]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题