Create symlink with pathlib

Question:

I want to test if Python code is working with symlinks properly. How can I create symlinks (e.g. equivalent to how os.symlink() can be used) in a faked filesystem based on pathlib.Path in a Python2/3 compatible way?

Asked By: thinwybk

||

Answers:

For Python 3.x, the pathlib package is in the standard library. For Python 2.7 you can use the backport pathlib2.

Both packages have a .symlink_to(target, target_is_directory=False) method which should do what you want.

From experience, Python 2 does not like to make symbolic links in Windows environments, but Python 3 supports NTFS symbolic links. Linux is happy making symlinks too. Other environments I can’t speak for.

Here is an example usage

In [1]: from pathlib import Path                                                                                                                                                                              

In [2]: Path('textfile.txt').write_text('hello world!')                                                                                                                                                       
Out[2]: 12

In [3]: print(list(Path('.').rglob('*.*')))                                                                                                                                                                   
[PosixPath('textfile.txt')]

In [4]: Path('link-to-textfile.txt').symlink_to(Path('textfile.txt'))                                                                                                                                         

In [5]: print(list(Path('.').rglob('*.*')))                                                                                                                                                                  
[PosixPath('textfile.txt'), PosixPath('link-to-textfile.txt')]

In [6]: Path('link-to-textfile.txt').read_text()                                                                                                                                                             
Out[6]: 'hello world!'
Answered By: Andrew F
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.