Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a relative symlink in python without using os.chdir()

Say I have a path to a file:

/path/to/some/directory/file.ext

In python, I'd like to create a symlink in the same directory as the file, that points to the file. I'd like to end up with this:

/path/to/some/directory/symlink -> file.ext

I can do this fairly easily using os.chdir() to cd into the directory and create the symlinks. But os.chdir() is not thread safe, so I'd like to avoid using it. Assuming that the current working directory of the process is not the directory with the file (os.getcwd() != '/path/to/some/directory'), what's the best way to do this?

I guess I could create a busted link in whatever directory I'm in, then move it to the directory with the file:

import os, shutil
os.symlink('file.ext', 'symlink')
shutil.move('symlink', '/path/to/some/directory/.')

Is there a better way to do this?

Note, I don't want to end up with is this:

/path/to/some/directory/symlink -> /path/to/some/directory/file.ext
like image 483
Josh Avatar asked Mar 20 '12 19:03

Josh


People also ask

How do you create a relative path in Python?

A relative path starts with / , ./ or ../ . To get a relative path in Python you first have to find the location of the working directory where the script or module is stored. Then from that location, you get the relative path to the file want.

Can symlinks be relative?

Symbolic link can be of two types Relative or Absolute.

How do you create a symbolic link in Python?

To create a symbolic link in Python, you can use the os module symlink() function.

How do you find the relative path of an absolute path in Python?

relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path. The existence of the given path or directory is not checked.


1 Answers

You could just set the second argument to the destination, like:

import os
os.symlink('file.ext', '/path/to/some/directory/symlink')
like image 177
tito Avatar answered Oct 15 '22 07:10

tito