This article shows how to create a symbolic link ("symlink" for short) using Python 3. The code below works on Unix-like operating systems like Linux and macOS. Windows compatibility is discussed here.
pathlib
(Python 3.4 and Up)On Python versions 3.4 and higher, we can create a symbolic link at mylink
that points to a file or directory target mytarget
by writing:
1 2 3 4 | from pathlib import Path p = Path( 'mylink' ) p.symlink_to( 'mytarget' ) |
Combining it into one line, we can write:
1 2 3 | from pathlib import Path Path( 'mylink' ).symlink_to( 'mytarget' ) |
The above examples use relative paths, which depend on the script user's current directory. We can also use absolute paths instead, like:
1 2 3 4 | from pathlib import Path p = Path( '/home/ubuntu/mylink' ) p.symlink_to( '/home/ubuntu/mytarget' ) |
We can also pass in a pathlib.Path
instead of a string to symlink_to
:
1 2 3 4 5 | from pathlib import Path link = Path( 'mylink' ) target = Path( 'mytarget' ) link.symlink_to( target ) |
os
On any version of Python 3 (or, if you're using Windows, Python 3.2 or higher), we can use the built-in os
library to create a symbolic link. To create a symbolic link at mylink
that points to a file or directory target mytarget
, we can write:
1 2 3 | import os os.symlink( 'mytarget', 'mylink' ) |
The above example uses relative paths, which depend on the script user's current directory. We can also use absolute paths instead, like:
1 2 3 4 5 | import os os.symlink( '/home/ubuntu/mytarget', '/home/ubuntu/mylink' ) |
The code examples in this article work properly on Unix-like operating systems like Linux and macOS.
On Windows, the code examples will work properly if you are using Python 3.8 or higher on an up-to-date version of Windows 10, either with "Developer Mode" enabled or with administrator privileges.
Specifically, the following issues must be resolved for the code to work on Windows:
os.symlink
requires Python 3.2 or higher (unlike Unix-like operating systems like Linux and macOS, where any version of Python 3 works), and pathlib
requires Python 3.4 or higher (which is true for all operating systems).target_is_directory
argument.