This is the header for the section on the os.symlink() function in official python 3.12 documentation, which is the version of python I am running:
os.symlink(src, dst, target_is_directory=False, *, dir_fd=None)
Create a symbolic link pointing to src named dst.
On Windows, a symlink represents either a file or a directory, and
does not morph to the target dynamically. If the target is present,
the type of the symlink will be created to match. Otherwise, the
symlink will be created as a directory if target_is_directory is True
or a file symlink (the default) otherwise. On non-Windows platforms,
target_is_directory is ignored.
No description is given for the fourth parameter (*) or for the fifth parameter(dir_fd).
I assume the fifth parameter means the directory in which to place the symlink, but I’m not sure I’m right. I totally missed the fourth parameter when I was writing my code, and now that I see it, I have no idea what to put there, and the docs don’t tell me.
This was my code, I know it’s wrong, but I don’t know what to put for the fourth parameter:
os.symlink(absold, newfn, False, dir)
However, the error message I got was not particularly helpful given that the doc mentions 4 if not 5 parameters.
TypeError: symlink() takes at most 3 positional arguments (4 given)
How do I code this so that the symlink is created in the directory I want it to be?
I am not running from the directory where these files are.
Are the official docs incorrect?
>Solution :
The * in function definition in python separates position and keyword-only arguments. You can’t do os.symlink(a, b, c, d), you have to os.symlink(a, b, c, dir_fd=d). It’s a normal python syntax. See https://docs.python.org/3/reference/compound_stmts.html#function-definitions :
Parameters after “*” or “*identifier” are keyword-only parameters and may only be passed by keyword arguments. Parameters before “/” are positional-only parameters and may only be passed by positional arguments.
As for dir_fd, it is a file descriptor refering to directory, a way to reference directories by a number on linux. See https://docs.python.org/3.12/library/os.html#dir-fd .