Relative Path to Your Project Directory

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]

How to write relative file path for a file in java project folder

You can use both your 1. and 3. option.

The 2. option would refer to C:/Users/Documents/producer/producer/krb5.conf.

For the purpose of testing you could try to get the absolute path from each file and print it.

        // 1.
File file1 = new File("krb5.conf");
File file2 = new File("producer/krb5.conf");
File file3 = new File("./krb5.conf");

System.out.println(file1.getAbsolutePath());
// Output: C:\Users\Documents\producer\krb5.conf

System.out.println(file2.getAbsolutePath());
// Output: C:\Users\Documents\producer\producer\krb5.conf

System.out.println(file3.getAbsolutePath());
// Output: C:\Users\Documents\producer\.\krb5.conf

The 3. path may look a bit weird at first, but it also works.

C:\Users\Documents\producer\. points to the current directory, so it is essentially the same as C:\Users\Documents\producer.

Relative path to your project directory

You can get current directory (directory of current file) with this

File.dirname(__FILE__)

You can then join it with relative path to the root

File.join(File.dirname(__FILE__), '../../') # add proper number of ..

Or you can use expand_path to convert relative path to absolute.

ENV['BUNDLE_GEMFILE'] = File.expand_path('../../Gemfile', File.dirname(__FILE__))

Or you can calculate relative path between two dirs.

require 'pathname'; 
puts Pathname.new('/').relative_path_from(Pathname.new('/some/child/dir/')).to_s
# => ../../..

How to read file from relative path in Java project? java.io.File cannot find the path specified

If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.

Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());

Or if all you're ultimately after is actually an InputStream of it:

InputStream input = getClass().getResourceAsStream("ListStopWords.txt");

This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.

If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.

Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));

Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.

How to define relative paths in Visual Studio Project?

If I get you right, you need ..\..\src

Defining relative paths for my Visual Studio Project files in c#

It turned out in the end that Visual Studio has a Macros option for this very task.

Sample Image

When you're looking at your include directories window as in the image above, there's a button labelled Macros. Click that, and it gives you access to a list of predefined paths. They all start with a $, like the ones already provided that point to the include folders for Visual Studio.

In my example above, I added $(MSBuildProjectDirectory), which points to the exact folder that I needed on the drive my code folder was located on. Hope I can help at least one or two people with this, cause it drove me insane until I came across it.

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.



Related Topics



Leave a reply



Submit