Reading a file using a relative path in a Python project

Relative paths are relative to current working directory. If you do not want your path to be relative, it must be absolute. But there is an often used trick to build an absolute path from current script: use its __file__ special attribute: from pathlib import Path path = Path(__file__).parent / “../data/test.csv” with path.open() as f: …

Read more

Why would a developer place a forward slash at the start of each relative path?

It’s done in order to root the path (making it an absolute path). It ensures that the path is not relative but read from the root of the site. This allows one to move a file around and not have to change the links to the different resources. Using your example: src=”https://stackoverflow.com/assets/js/jquery.js” If the referencing …

Read more

How to use relative paths without including the context root name?

If your actual concern is the dynamicness of the webapp context (the “AppName” part), then just retrieve it dynamically by HttpServletRequest#getContextPath(). <head> <link rel=”stylesheet” href=”https://stackoverflow.com/questions/4764405/${pageContext.request.contextPath}/templates/style/main.css” /> <script src=”${pageContext.request.contextPath}/templates/js/main.js”></script> <script>var base = “${pageContext.request.contextPath}”;</script> </head> <body> <a href=”${pageContext.request.contextPath}/pages/foo.jsp”>link</a> </body> If you want to set a base path for all relative links so that you don’t need to …

Read more

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let’s say that your image is inside a subfolder named pictures/: Absolute path If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That’s why you need to specify your document’s folder …

Read more