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

前端 未结 3 472
半阙折子戏
半阙折子戏 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)
    

提交回复
热议问题