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: Unknown Arguments Using *arguments

If your function can take in any number of arguments then add a * in front of the parameter name:

def myfunc(*arguments):
 for a in arguments:
   print a
myfunc(a)
myfunc(a,b)
myfunc(a,b,c)