R command for setting working directory to source file location in Rstudio

To get the location of a script being sourced, you can use utils::getSrcDirectory or utils::getSrcFilename. So changing the working directory to that of the current file can be done with: setwd(getSrcDirectory()[1]) This does not work in RStudio if you Run the code rather than Sourceing it. For that, you need to use rstudioapi::getActiveDocumentContext. setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) This … Read more

Changing the current working directory in Java?

There is no reliable way to do this in pure Java. Setting the user.dir property via System.setProperty() or java -Duser.dir=… does seem to affect subsequent creations of Files, but not e.g. FileOutputStreams. The File(String parent, String child) constructor can help if you build up your directory path separately from your file path, allowing easier swapping. … Read more

How to get the current directory in a C program?

Have you had a look at getcwd()? #include <unistd.h> char *getcwd(char *buf, size_t size); Simple example: #include <unistd.h> #include <stdio.h> #include <limits.h> int main() { char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd)) != NULL) { printf(“Current working dir: %s\n”, cwd); } else { perror(“getcwd() error”); return 1; } return 0; }

python: Change the scripts working directory to the script’s own directory

This will change your current working directory to so that opening relative paths will work: import os os.chdir(“/home/udi/foo”) However, you asked how to change into whatever directory your Python script is located, even if you don’t know what directory that will be when you’re writing your script. To do this, you can use the os.path … Read more

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, … Read more

How do you properly determine the current script directory?

os.path.dirname(os.path.abspath(__file__)) is indeed the best you’re going to get. It’s unusual to be executing a script with exec/execfile; normally you should be using the module infrastructure to load scripts. If you must use these methods, I suggest setting __file__ in the globals you pass to the script so it can read that filename. There’s no … Read more