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));
}
How to get path relative to the working directory?
Give this a try.
@ECHO OFF
SETLOCAL EnableDelayedExpansion
for /r %%F in (*.txt) do (
echo %%F|findstr /I /G:exclude.txt >nul 2>&1
IF NOT "!ERRORLEVEL!"=="0" (
REM do something here
)
)
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.
Relative paths based on file location instead of current working directory
What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}
) and then use this to get the parent directory and cd
to it at the beginning of the script.
#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$parent_path"
cat ../some.text
This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh
inside dir
.
Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)
Resolve relative path relative to another path instead of current working directory
why not just:
path.resolve(__dirname, p)
__dirname
works a bit differently and returns the current modules path, which can then be joined easily with the relative path.
How to get current relative directory of your Makefile?
The shell function.
You can use shell
function: current_dir = $(shell pwd)
.
Or shell
in combination with notdir
, if you need not absolute path:current_dir = $(notdir $(shell pwd))
.
Update.
Given solution only works when you are running make
from the Makefile's current directory.
As @Flimm noted:
Note that this returns the current working directory, not the parent directory of the Makefile.
For example, if you runcd /; make -f /home/username/project/Makefile
, thecurrent_dir
variable will be/
, not/home/username/project/
.
Code below will work for Makefiles invoked from any directory:
mkfile_path := $(abspath $(lastword $(MAKEFILE_LIST)))
current_dir := $(notdir $(patsubst %/,%,$(dir $(mkfile_path))))
Get path of file relative to some directory in C#
I think you're looking for Path.GetRelativePath(...)
. Used like this:
string FileDirectory = "/tmp/simple";
string fullPath = "/tmp/simple/s1/s1.txt";
string result = Path.GetRelativePath(FileDirectory, fullPath);
// s1\s1.txt
To get the result with forward slash /
instead, you can do a simple Replace()
on the result:
result = result.Replace("\\", "/");
// s1/s1.txt
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
Mvc3 Razor Dropdownlistfor Enums
Sending Arguments to Background Worker
Difference Between Convert.Tostring() and .Tostring()
System.Outofmemoryexception' Was Thrown When There Is Still Plenty of Memory Free
Operator Overloading with C# Extension Methods
How to Generate an Image from Text on Fly at Runtime
Thread Safe C# Singleton Pattern
How to Access an Internal Class from an External Assembly
Why Is "Set as Startup" Option Stored in the Suo File and Not the Sln File
Stop Tabcontrol from Recreating Its Children
How to Change the File Location Programmatically
How to Change the Color of Progressbar in C# .Net 3.5
How to Transform String to Utf-8 in C#
How to Pass Values Across the Pages in ASP.NET Without Using Session
C# Winforms Combobox Dynamic Autocomplete