The Python os.link() method creates a hard link pointing to src named dst. This method is used for creating a copy of existing file.
In Python, creating a hard link means generating another reference to a file. It allows multiple file names to point to the same existing file.
SyntaxFollowing is the syntax for Python os.link() method −
os.link(src, dst)Parameters
The Python os.link() method accepts the following parameters −
src − This is the source file path for which hard link would be created.
dest − This is the target file path where hard link would be created.
The Python os.link() method does not return any value.
ExampleThe following example shows the usage of link() method. Here, we are creating a hard link for the file named "txtFile.txt".
import os, sys # Open a file path = "txtFile.txt" fd = os.open( path, os.O_RDWR|os.O_CREAT ) # Close opened file os.close( fd ) # Now create another copy of the above file dst = "/tmp/newFile.txt" os.link( path, dst) print ("Created hard link successfully!!")
This would produce following result −
Created hard link successfully!!Example
Suppose, we are trying to create a hard link. If a hard link at the destination already exists, the "os.link()" method will throw a File exists exception as shown in the below example.
import os # Open a file path = "foo.txt" fd = os.open( path, os.O_RDWR|os.O_CREAT ) # Close opened file os.close( fd ) # Now create another copy of the above file dst = "/tmp/newFile.txt" # Creating a hard link try: os.link( path, dst) print("Hard link created successfully.") except Exception as e: print(f"Error: {e}")
This would produce following result −
Error: [Errno 17] File exists: 'foo.txt' -> '/tmp/newFile.txt'
python_files_io.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4