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 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

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/os/python-os-exercise-6.php