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

Say I have a file path:

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

In python, I would like to create a symbolic link in the same directory as the file that points to the file. I would like to end up with:

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

I can do this quite easily using os.chdir () in cd to a directory and create symbolic links. But os.chdir () is not thread safe, so I would like to avoid using this. Assuming the current working directory of the process is not the directory with the file (os.getcwd ()! = '/ Path / to / some / directory'), what is the best way to do this?

I think I could create an enumeration link in any directory I am 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?

Notice I do not want this to end:

/path/to/some/directory/symlink -> /path/to/some/directory/file.ext
+5
2

, :

import os
os.symlink('file.ext', '/path/to/some/directory/symlink')
+12

os.path.relpath(), . , script foo/, src/ dst/, dst/, src/. :

import os
from glob import glob
for src_path in glob('src/*'):
    os.symlink(
        os.path.relpath(
            src_path,
            'dst/'
        ),
        os.path.join('dst', os.path.basename(src_path))
    )

dst/ :

1.txt -> ../src/1.txt
2.txt -> ../src/2.txt

, tarball foo, , tar , tarball.

+14
source

All Articles