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

前端 未结 3 458
半阙折子戏
半阙折子戏 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: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 != [] ]
    

提交回复
热议问题