Python: Create a symbolic link and read it to decide the original file pointed by the link
6. Symbolic Link Creator
Write a Python program to create a symbolic link and read it to determine the original file pointed to by the link.
Sample Solution:
Python Code :
import os
path = '/tmp/' + os.path.basename(__file__)
print('Creating link {} -> {}'.format(path, __file__))
os.symlink(__file__, path)
stat_info = os.lstat(path)
print('\nFile Permissions:', oct(stat_info.st_mode))
print('\nPoints to:', os.readlink(path))
#removes the file path
os.unlink(path)
Sample Output:
Creating link /tmp/main.py -> /tmp/sessions/af6c4b4e3816cd19/main.py File Permissions: 0o120777 Points to: /tmp/sessions/af6c4b4e3816cd19/main.py
For more Practice: Solve these Related Problems:
- Write a Python program to create a symbolic link for a given file using os.symlink() and then use os.readlink() to display the target file.
- Write a Python script that creates a symlink for a file, verifies the link with os.path.islink(), and then prints the absolute path of the original file.
- Write a Python function that creates a symbolic link, deletes the original file, and then attempts to read the symlink, handling the resulting error.
- Write a Python program to generate a symbolic link for a file and then compare its target with a given expected path.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to get the size, permissions, owner, device, created, last modified and last accessed date time of a specified path.
Next: Write a Python program to create a file and write some text and rename the file name.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.