How to Open Files Relative to Home Directory

How to open files relative to home directory

  1. The shell (bash, zsh, etc) is responsible for wildcard expansion, so in your first example there's no shell, hence no expansion. Using the tilde to point to $HOME is a mere convention; indeed, if you look at the documentation for File.expand_path, it correctly interprets the tilde, but it's a feature of the function itself, not something inherent to the underlying system; also, File.expand_path requires the $HOME environment variable to be correctly set. Which bring us to the possible alternative...
  2. Try this:

    open(ENV['HOME']+'/some_file')

I hope it's slick enough. I personally think using an environment variable is semantically clearer than using expand_path.

How to open files relative to home directory

  1. The shell (bash, zsh, etc) is responsible for wildcard expansion, so in your first example there's no shell, hence no expansion. Using the tilde to point to $HOME is a mere convention; indeed, if you look at the documentation for File.expand_path, it correctly interprets the tilde, but it's a feature of the function itself, not something inherent to the underlying system; also, File.expand_path requires the $HOME environment variable to be correctly set. Which bring us to the possible alternative...
  2. Try this:

    open(ENV['HOME']+'/some_file')

I hope it's slick enough. I personally think using an environment variable is semantically clearer than using expand_path.

How to open file with path relative to c file, not working directory

Based on our conversation in the comments, you have several alternatives, which I'll list below from, IMHO, most to least desirable.

You never specified if you were in Windows, GNU+Linux, or were doing cross-platform development, but I'm sure you can adapt the suggestions to your platform.

Multiple and Custom Config Files (Recommended)

You could modify your program to look at your platform's standard location for program data and/or configuration files. For example, you could have it look for a standard config at /etc/<your-program>/default.conf in GNU+Linux or %APPDATA%\<your-program>\default.conf in Windows.

If different users need to use their own personal configs, the program could also be made to accept a config file path as an argument. For example:

GNU+Linux:

$ ./your-program --config ${HOME}/.your-program/my.conf

Windows:

> your-program.exe --config %userprofile%\your-program\my.conf

Note that the use of %userprofile% may change based on Windows versions and/or shells used (e.g. standard cmd.exe vs powershell).

Compiling in the Path (Not Recommended)

Based on your comments, a short-term workaround could be to compile the absolute path into it for the __FILE__ macro to give that back to you at runtime. As I said in my comment:

if you're completely sure about the program always being placed in the same directory for everyone, then you can set the absolute path shown by the __FILE__ macro if you send the full path when compiling; e.g. gcc $(pwd)/your-file.c, when it prints __FILE__ will show the full path it had at compile time, not run-time. (Can't add enough disclaimers here, though)

Please note that there're many reasons to not use this approach. I'm simply suggesting it as a short-term workaround to pull out of an existing crisis-level situation you may have, while you (hopefully) take a closer look at the more desirable approach to handle configurations and path-finding.

How do I open a file in python with a relative path using with open()?

You can do it with:

import os
path = os.getenv('HOME') + '/scripts/config.yaml'

~ only works in shell, not in a Python string

How can I open files relative to my GOPATH?

Hmm... the path/filepath package has Abs() which does what I need (so far) though it's a bit inconvenient:

absPath, _ := filepath.Abs("../mypackage/data/file.txt")

Then I use absPath to load the file and it works fine.

Note that, in my case, the data files are in a package separate from the main package from which I'm running the program. If it was all in the same package, I'd remove the leading ../mypackage/. Since this path is obviously relative, different programs will have different structures and need this adjusted accordingly.

If there's a better way to use external resources with a Go program and keep it portable, feel free to contribute another answer.

Opening files by relative path on Windows using C

It depends on where the current working directory needs to be when you run each of the test executables. What I would do is use GetModuleFileName to get the location of the executable, then chop off the name of the exe and the bin to get the root directory as an absolute path.

Each executable name can be created by then concatenating the root directorty with (for example) "out\\test1\\test1.exe"

If you need to set the current directory to the test directory, just concatenate "out\\test1" to the root directory and use SetCurrentDirectory to set the current working directoy. Then you can run the executable with just its name e.g. test1.exe

Reading file using relative path in 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:
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 open a file with relative path in C++?

What you are using is not at all a relative path. Sure you are using the relative path syntax but not the actual meaning of what it is.

/../../../../../../source/Project/components/Project/test/file.dat

This path starts with a / which means root then finds it parent which return root again since root has no parent and goes on... The simplified version of this is:

/source/Project/components/Project/test/file.dat

So it will look for folder source in root which of-course doesn't exist.

What you should do is something like this (assuming your code is in project folder):

./test/file.dat

or if it is in some other folder within Project folder you can do something like this:

../test/file.dat

../ take you to the parent of your current code directory which under this case's assumption is Project.



Related Topics



Leave a reply



Submit