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?
symlink() method in Python is used to create symbolic link. This method creates symbolic link pointing to source named destination. To read about symbolic links/soft links, please refer to this article.
The Pathlib module in Python deals with path related tasks, such as constructing new paths from names of files and from other paths, checking for various properties of paths and creating files and folders at specific paths.
Since Python 3.4, pathlib has been available in the standard library. With pathlib , file paths can be represented by proper Path objects instead of plain strings as before. These objects make code dealing with file paths: Easier to read, especially because / is used to join paths together.
That is the Pathlib, which is also a Python built-in library. It is more intuitive in terms of syntax, easier to use and has more features out of the box.
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 in either. 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!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With