os.path.abspath('file1.txt') doesn't return the correct path

后端 未结 5 1606
被撕碎了的回忆
被撕碎了的回忆 2020-12-18 07:49

Say the path of the file \'file1.txt\' is /home/bentley4/Desktop/sc/file1.txt Say my current working directory is /home/bentley4

i         


        
相关标签:
5条回答
  • 2020-12-18 08:23

    You will get the path with os.path.abspath(__file__).

    0 讨论(0)
  • 2020-12-18 08:32

    The problem should be that previously the cwd was changed using the os.chdir(another_path) and it's still loaded in the context of the current execution. so the fix should be restore the original path after the use of the task in another_path has finish.
    Example :

      original_path = os.getcwd()
      os.chdir(another_path) 
      # here perform some operation over another_path
      os.chdir(original_path ) # here is the restore of the original path
    
    0 讨论(0)
  • 2020-12-18 08:36

    abspath just builds a path, it doesn't check anything about files existing.

    From the docs:

    On most platforms, this is equivalent to normpath(join(os.getcwd(), path)).

    0 讨论(0)
  • 2020-12-18 08:39

    os.path.abspath(filename) returns an absolute path as seen from your current working directory. It does no checking whether the file actually exists.

    If you want the absolute path of /home/bentley4/Desktop/sc/file1.txt and you are in /home/bentley4 you will have to use os.path.abspath("Desktop/sc/file1.txt").

    0 讨论(0)
  • 2020-12-18 08:41

    I was working on the same issue and I found this, hope it helps you:

    os.path.join(root, f)

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