I am new to programming, so I am confused. I know that relative path is a way to specify the location of a directory relative to another directory.

But I don't understand why do I need relative path. Could you please give me an example?

有帮助吗?

解决方案 2

Absolute path is the full directory path .

Relative path is relative to the directory you are in, so if you are in the above directory, then if you reference file test.txt as relative, it assumes the same directory you are in. When you do ../ then it goes back one directory.

Suppose you are in a directory whose path is k... In this directory there is a file named a.txt. Now

the absolute path is C:\A\B\a.txt

the relative path is a.txt (as you are in the same directory).

Why you need a relative path

You need a relative path so that in your code you can use any file without depending on the path set by user. For example in your code you need to access a file. If you use absolute path then the path will change depending on the location where the user will set it.

But if you use relative path then the path will be always same as it will always be in your project folder. (or a fixed hiararchy)

其他提示

why do I need relative path

So that when you ship your code, you don't have to worry about where the user will put that code, while using a path to some resource.
You can use a path relative to the project root, which will be same regardless of where the project is.

Great question. I've noticed relative paths are extremely helpful when dealing with larger sites that have a test or staging area, then the actual live site.

For example, say you have TEST.MYSITE.COM which in turn gets pushed out to WWW.MYSITE.COM. In this example, relative links do not need to be updated because you test the file, the push live when it meets your expectations.

Lets say you have an html file that references TEST.MYSITE.COM/MYFOLDER/MYIMAGE.JPG and you would like to update this image. After the image has been corrected, if you are not using relative links, you would then need to change the image name on the html file from "TEST.MYSITE.COM/MYFOLDER/MYIMAGE.JPG" to "WWW.MYSITE.COM/MYFOLDER/MYIMAGE.JPG".

If one was using the relative link "/MYFOLDER/MYIMAGE.JPG" this would not need to get updated. You could only imagine how this example would get multiplied throughout the site, which would then become a tedious process.

Relative links help avoid this. Hopefully this makes some sense. It sounds like you know what they are, this was just attempting to answer "why do I need relative path[s]".

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top