How to Set Relative Path to Current Folder

How to set relative path to current folder?

Just dot is working. The doctype makes a difference however as sometimes the ./ is fine as well.

<a href=".">Link to this folder</a>

Relative paths in Python

In the file that has the script, you want to do something like this:

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its package resources API instead.

UPDATE: I'm responding to a comment here so I can paste a code sample. :-)

Am I correct in thinking that __file__ is not always available (e.g. when you run the file directly rather than importing it)?

I'm assuming you mean the __main__ script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):

#foo.py
import os
print os.getcwd()
print __file__

#in the interactive interpreter
>>> import foo
/Users/jason
foo.py

#and finally, at the shell:
~ % python foo.py
/Users/jason
foo.py

However, I do know that there are some quirks with __file__ on C extensions. For example, I can do this on my Mac:

>>> import collections #note that collections is a C extension in Python 2.5
>>> collections.__file__
'/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-
dynload/collections.so'

However, this raises an exception on my Windows machine.

Getting path relative to the current working directory?

If you don't mind the slashes being switched, you could [ab]use Uri:

Uri file = new Uri(@"c:\foo\bar\blop\blap.txt");
// Must end in a slash to indicate folder
Uri folder = new Uri(@"c:\foo\bar\");
string relativePath =
Uri.UnescapeDataString(
folder.MakeRelativeUri(file)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);

As a function/method:

string GetRelativePath(string filespec, string folder)
{
Uri pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
folder += Path.DirectorySeparatorChar;
}
Uri folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
}

Absolute Path from Relative Path with a different current folder

If you're currently in c:\test and you want to get c:\MyOtherFolder\foo.bar without knowing that you're in c:\test you want to do;

 Environment.CurrentDirectory = @"..\MyOtherFolder"; //navigation accepts relative path
string fullPath = Directory.GetCurrentDirectory(); // returns full path

After that you may want to set the current directory back to your previous location.

Relative path to current directory in code-behind isn't consistent

Getting a path can be tricky in asp.net.

Here are four different ways to get your current path most only two provide the same results. Put this below in server side code. I like using the AppDomain it seems the most reliable in finding where your .aspx pages are located.

string paths = " Runtime Path "  + System.Reflection.Assembly.GetExecutingAssembly().Location + "<br>" +
" Using Root " + new DirectoryInfo("./").FullName + "<br>" +
" Appdomain " + Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile) + "<br>" +
" Environment " + System.Environment.CurrentDirectory;

The results I got were. Hope this helps.

Runtime Path C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\e333f875\41caca57\assembly\dl3\9d915b4e\ee11a5b0_20d4cd01\MvcTutorial.DLL

Using Root C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\

Appdomain C:\Users\Robert\documents\visual studio 2010\Projects\MvcTutorial\MvcTutorial

Environment C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0

Java - How to create a file in a directory using relative Path

File dir = new File("tmp/test");
dir.mkdirs();
File tmp = new File(dir, "tmp.txt");
tmp.createNewFile();

BTW: For testing use @Rule and TemporaryFolder class to create temp files or folders

Get relative path of files in sub-folders from the current directory

The Resolve-Path cmdlet has a -Relative parameter that will return a path relative to the current directory:

Set-Location C:\MyScript
$relativePath = Get-Item Data\Test.txt | Resolve-Path -Relative

Reading file using relative path in python project

Relative paths are relative to current working directory.
If you do not your want your path to be, 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:
test = list(csv.reader(f))

This requires python 3.4+ (for the pathlib module).

If you still need to support older versions, you can get the same result with:

import csv
import os.path

my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
test = list(csv.reader(f))

[2020 edit: python3.4+ should now be the norm, so I moved the pathlib version inspired by jpyams' comment first]



Related Topics



Leave a reply



Submit