When to use Absolute Path vs Relative Path in Python
Asked Answered
V

2

13

For reference. The absolute path is the full path to some place on your computer. The relative path is the path to some file with respect to your current working directory (PWD). For example:

Absolute path: C:/users/admin/docs/stuff.txt

If my PWD is C:/users/admin/, then the relative path to stuff.txt would be: docs/stuff.txt

Note, PWD + relative path = absolute path.

Cool, awesome. Now, I wrote some scripts which check if a file exists.

os.chdir("C:/users/admin/docs") os.path.exists("stuff.txt")

This returns TRUE if stuff.txt exists and it works.

Now, instead if I write,

os.path.exists("C:/users/admin/docs/stuff.txt")

This also returns TRUE.

Is there a definite time when we need to use one over the other? Is there a methodology for how python looks for paths? Does it try one first then the other?

Thanks!

Vespertine answered 27/6, 2017 at 3:54 Comment(2)
Apparently you can only use Absolute Path for os.path.getsize() so I'm even more confused.Vespertine
I can't recall ever having a problem when using an absolute path... though I wonder how it's handled internallyRhines
L
13

If you don't know where the user will be executing the script from, it is best to compute the absolute path on the user's system using os and __file__.

__file__ is a global variable set on every Python script that returns the relative path to the *.py file that contains it.

import os
my_absolute_dirpath = os.path.abspath(os.path.dirname(__file__))
Leshalesher answered 8/9, 2017 at 3:20 Comment(0)
S
6

The biggest consideration is probably portability. If you move your code to a different computer and you need to access some other file, where will that other file be? If it will be in the same location relative to your program, use a relative address. If it will be in the same absolute location, use an absolute address.

Socher answered 27/6, 2017 at 4:22 Comment(1)
Agreed.. in general, I hate when programs I'm using insist on a particular folder. Imagine if python itself insisted your code be in some exact folder that you couldn't change. Sometimes it matters more than others, though.Zins

© 2022 - 2024 — McMap. All rights reserved.