w3resource

Python: Create a symbolic link and read it to decide the original file pointed by the link

Python Operating System Services: Exercise-6 with Solution

Write a Python program to create a symbolic link and read it to decide the original file pointed 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

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 Python skills with w3resource's quiz



Python: Tips of the Day

Python: Unpack a Tuple

>>> items = (0, 'b', 'one', 10,  11, 'zero')
>>> a, b, c, d, e, f = items
>>> print(f)
zero
>>> a, *b, c = items
>>> print(b)
['b', 'one', 10, 11]
>>> *_, a, b = items
>>> print(a)
11