os — Miscellaneous operating system interfaces¶
Source code: Lib/os.py
This module provides a portable way of using operating system dependent
functionality. If you just want to read or write a file see open(), if
you want to manipulate paths, see the os.path module, and if you want to
read all the lines in all the files on the command line see the fileinput
module. For creating temporary files and directories see the tempfile
module, and for high-level file and directory handling see the shutil
module.
Notes on the availability of these functions:
The design of all built-in operating system dependent modules of Python is such that as long as the same functionality is available, it uses the same interface; for example, the function
os.stat(path)returns stat information about path in the same format (which happens to have originated with the POSIX interface).Extensions peculiar to a particular operating system are also available through the
osmodule, but using them is of course a threat to portability.All functions accepting path or file names accept both bytes and string objects, and result in an object of the same type, if a path or file name is returned.
On VxWorks, os.popen, os.fork, os.execv and os.spawn*p* are not supported.
On WebAssembly platforms, Android and iOS, large parts of the
osmodule are not available or behave differently. APIs related to processes (e.g.fork(),execve()) and resources (e.g.nice()) are not available. Others likegetuid()andgetpid()are emulated or stubs. WebAssembly platforms also lack support for signals (e.g.kill(),wait()).
Note
All functions in this module raise OSError (or subclasses thereof) in
the case of invalid or inaccessible file names and paths, or other arguments
that have the correct type, but are not accepted by the operating system.
- os.name¶
The name of the operating system dependent module imported. The following names have currently been registered:
'posix','nt','java'.See also
sys.platformhas a finer granularity.os.uname()gives system-dependent version information.The
platformmodule provides detailed checks for the system’s identity.
File Names, Command Line Arguments, and Environment Variables¶
In Python, file names, command line arguments, and environment variables are
represented using the string type. On some systems, decoding these strings to
and from bytes is necessary before passing them to the operating system. Python
uses the filesystem encoding and error handler to perform this
conversion (see sys.getfilesystemencoding()).
The filesystem encoding and error handler are configured at Python
startup by the PyConfig_Read() function: see
filesystem_encoding and
filesystem_errors members of PyConfig.
Changed in version 3.1: On some systems, conversion using the file system encoding may fail. In this case, Python uses the surrogateescape encoding error handler, which means that undecodable bytes are replaced by a Unicode character U+DCxx on decoding, and these are again translated to the original byte on encoding.
The file system encoding must
guarantee to successfully decode all bytes below 128. If the file system
encoding fails to provide this guarantee, API functions can raise
UnicodeError.
See also the locale encoding.
Python UTF-8 Mode¶
Added in version 3.7: See PEP 540 for more details.
The Python UTF-8 Mode ignores the locale encoding and forces the usage of the UTF-8 encoding:
Use UTF-8 as the filesystem encoding.
sys.getfilesystemencoding()returns'utf-8'.locale.getpreferredencoding()returns'utf-8'(the do_setlocale argument has no effect).sys.stdin,sys.stdout, andsys.stderrall use UTF-8 as their text encoding, with thesurrogateescapeerror handler being enabled forsys.stdinandsys.stdout(sys.stderrcontinues to usebackslashreplaceas it does in the default locale-aware mode)On Unix,
os.device_encoding()returns'utf-8'rather than the device encoding.
Note that the standard stream settings in UTF-8 mode can be overridden by
PYTHONIOENCODING (just as they can be in the default locale-aware
mode).
As a consequence of the changes in those lower level APIs, other higher level APIs also exhibit different default behaviours:
Command line arguments, environment variables and filenames are decoded to text using the UTF-8 encoding.
os.fsdecode()andos.fsencode()use the UTF-8 encoding.open(),io.open(), andcodecs.open()use the UTF-8 encoding by default. However, they still use the strict error handler by default so that attempting to open a binary file in text mode is likely to raise an exception rather than producing nonsense data.
The Python UTF-8 Mode is enabled if the LC_CTYPE locale is
C or POSIX at Python startup (see the PyConfig_Read()
function).
It can be enabled or disabled using the -X utf8 command line
option and the PYTHONUTF8 environment variable.
If the PYTHONUTF8 environment variable is not set at all, then the
interpreter defaults to using the current locale settings, unless the current
locale is identified as a legacy ASCII-based locale (as described for
PYTHONCOERCECLOCALE), and locale coercion is either disabled or
fails. In such legacy locales, the interpreter will default to enabling UTF-8
mode unless explicitly instructed not to do so.
The Python UTF-8 Mode can only be enabled at the Python startup. Its value
can be read from sys.flags.utf8_mode.
See also the UTF-8 mode on Windows and the filesystem encoding and error handler.
See also
- PEP 686
Python 3.15 will make Python UTF-8 Mode default.
Process Parameters¶
These functions and data items provide information and operate on the current process and user.
- os.ctermid()¶
Return the filename corresponding to the controlling terminal of the process.
Availability: Unix, not WASI.
- os.environ¶
A mapping object where keys and values are strings that represent the process environment. For example,
environ['HOME']is the pathname of your home directory (on some platforms), and is equivalent togetenv("HOME")in C.This mapping is captured the first time the
osmodule is imported, typically during Python startup as part of processingsite.py. Changes to the environment made after this time are not reflected inos.environ, except for changes made by modifyingos.environdirectly.This mapping may be used to modify the environment as well as query the environment.
putenv()will be called automatically when the mapping is modified.On Unix, keys and values use
sys.getfilesystemencoding()and'surrogateescape'error handler. Useenvironbif you would like to use a different encoding.On Windows, the keys are converted to uppercase. This also applies when getting, setting, or deleting an item. For example,
environ['monty'] = 'python'maps the key'MONTY'to the value'python'.Note
Calling
putenv()directly does not changeos.environ, so it’s better to modifyos.environ.Note
On some platforms, including FreeBSD and macOS, setting
environmay cause memory leaks. Refer to the system documentation forputenv().You can delete items in this mapping to unset environment variables.
unsetenv()will be called automatically when an item is deleted fromos.environ, and when one of thepop()orclear()methods is called.See also
The
os.reload_environ()function.Changed in version 3.9: Updated to support PEP 584’s merge (
|) and update (|=) operators.
- os.environb¶
Bytes version of
environ: a mapping object where both keys and values arebytesobjects representing the process environment.environandenvironbare synchronized (modifyingenvironbupdatesenviron, and vice versa).environbis only available ifsupports_bytes_environisTrue.Added in version 3.2.
Changed in version 3.9: Updated to support PEP 584’s merge (
|) and update (|=) operators.
- os.reload_environ()¶
The
os.environandos.environbmappings are a cache of environment variables at the time that Python started. As such, changes to the current process environment are not reflected if made outside Python, or byos.putenv()oros.unsetenv(). Useos.reload_environ()to updateos.environandos.environbwith any such changes to the current process environment.Warning
This function is not thread-safe. Calling it while the environment is being modified in an other thread is an undefined behavior. Reading from
os.environoros.environb, or callingos.getenv()while reloading, may return an empty result.Added in version 3.14.
- os.chdir(path)
- os.fchdir(fd)
- os.getcwd()
These functions are described in Files and Directories.
- os.fsencode(filename)¶
Encode path-like filename to the filesystem encoding and error handler; return
bytesunchanged.fsdecode()is the reverse function.Added in version 3.2.
Changed in version 3.6: Support added to accept objects implementing the
os.PathLikeinterface.
- os.fsdecode(filename)¶
Decode the path-like filename from the filesystem encoding and error handler; return
strunchanged.fsencode()is the reverse function.Added in version 3.2.
Changed in version 3.6: Support added to accept objects implementing the
os.PathLikeinterface.
- os.fspath(path)¶
Return the file system representation of the path.
If
strorbytesis passed in, it is returned unchanged. Otherwise__fspath__()is called and its value is returned as long as it is astrorbytesobject. In all other cases,TypeErroris raised.Added in version 3.6.
- class os.PathLike¶
An abstract base class for objects representing a file system path, e.g.
pathlib.PurePath.Added in version 3.6.
- os.getenv(key, default=None)¶
Return the value of the environment variable key as a string if it exists, or default if it doesn’t. key is a string. Note that since
getenv()usesos.environ, the mapping ofgetenv()is similarly also captured on import, and the function may not reflect future environment changes.On Unix, keys and values are decoded with
sys.getfilesystemencoding()and'surrogateescape'error handler. Useos.getenvb()if you would like to use a different encoding.Availability: Unix, Windows.
- os.getenvb(key, default=None)¶
Return the value of the environment variable key as bytes if it exists, or default if it doesn’t. key must be bytes. Note that since
getenvb()usesos.environb, the mapping ofgetenvb()is similarly also captured on import, and the function may not reflect future environment changes.getenvb()is only available ifsupports_bytes_environisTrue.Availability: Unix.
Added in version 3.2.
- os.get_exec_path(env=None)¶
Returns the list of directories that will be searched for a named executable, similar to a shell, when launching a process. env, when specified, should be an environment variable dictionary to lookup the PATH in. By default, when env is
None,environis used.Added in version 3.2.
- os.getegid()¶
Return the effective group id of the current process. This corresponds to the “set id” bit on the file being executed in the current process.
Availability: Unix, not WASI.
- os.geteuid()¶
Return the current process’s effective user id.
Availability: Unix, not WASI.
- os.getgid()¶
Return the real group id of the current process.
Availability: Unix.
The function is a stub on WASI, see WebAssembly platforms for more information.
- os.getgrouplist(user, group, /)¶
Return list of group ids that user belongs to. If group is not in the list, it is included; typically, group is specified as the group ID field from the password record for user, because that group ID will otherwise be potentially omitted.
Availability: Unix, not WASI.
Added in version 3.3.
- os.getgroups()¶
Return list of supplemental group ids associated with the current process.
Availability: Unix, not WASI.
Note
On macOS,
getgroups()behavior differs somewhat from other Unix platforms. If the Python interpreter was built with a deployment target of10.5or earlier,getgroups()returns the list of effective group ids associated with the current user process; this list is limited to a system-defined number of entries, typically 16, and may be modified by calls tosetgroups()if suitably privileged. If built with a deployment target greater than10.5,getgroups()returns the current group access list for the user associated with the effective user id of the process; the group access list may change over the lifetime of the process, it is not affected by calls tosetgroups(), and its length is not limited to 16. The deployment target value,MACOSX_DEPLOYMENT_TARGET, can be obtained withsysconfig.get_config_var().
- os.getlogin()¶
Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use
getpass.getuser()since the latter checks the environment variablesLOGNAMEorUSERNAMEto find out who the user is, and falls back topwd.getpwuid(os.getuid())[0]to get the login name of the current real user id.Availability: Unix, Windows, not WASI.
- os.getpgid(pid)¶
Return the process group id of the process with process id pid. If pid is 0, the process group id of the current process is returned.
Availability: Unix, not WASI.
- os.getpgrp()¶
Return the id of the current process group.
Availability: Unix, not WASI.
- os.getpid()¶
Return the current process id.
The function is a stub on WASI, see WebAssembly platforms for more information.
- os.getppid()¶
Return the parent’s process id. When the parent process has exited, on Unix the id returned is the one of the init process (1), on Windows it is still the same id, which may be already reused by another process.
Availability: Unix, Windows, not WASI.
Changed in version 3.2: Added support for Windows.
- os.getpriority(which, who)¶
Get program scheduling priority. The value which is one of
PRIO_PROCESS,PRIO_PGRP, orPRIO_USER, and who is interpreted relative to which (a process identifier forPRIO_PROCESS, process group identifier forPRIO_PGRP, and a user ID forPRIO_USER). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process.Availability: Unix, not WASI.
Added in version 3.3.
- os.PRIO_PROCESS¶
- os.PRIO_PGRP¶
- os.PRIO_USER¶
Parameters for the
getpriority()andsetpriority()functions.Availability: Unix, not WASI.
Added in version 3.3.
- os.PRIO_DARWIN_THREAD¶
- os.PRIO_DARWIN_PROCESS¶
- os.PRIO_DARWIN_BG¶
- os.PRIO_DARWIN_NONUI¶
Parameters for the
getpriority()andsetpriority()functions.Availability: macOS
Added in version 3.12.
- os.getresuid()¶
Return a tuple (ruid, euid, suid) denoting the current process’s real, effective, and saved user ids.
Availability: Unix, not WASI.
Added in version 3.2.
- os.getresgid()¶
Return a tuple (rgid, egid, sgid) denoting the current process’s real, effective, and saved group ids.
Availability: Unix, not WASI.
Added in version 3.2.
- os.getuid()¶
Return the current process’s real user id.
Availability: Unix.
The function is a stub on WASI, see WebAssembly platforms for more information.
- os.initgroups(username, gid, /)¶
Call the system
initgroups()to initialize the group access list with all of the groups of which the specified username is a member, plus the specified group id.Availability: Unix, not WASI, not Android.
Added in version 3.2.
- os.putenv(key, value, /)¶
Set the environment variable named key to the string value. Such changes to the environment affect subprocesses started with
os.system(),popen()orfork()andexecv().Assignments to items in
os.environare automatically translated into corresponding calls toputenv(); however, calls toputenv()don’t updateos.environ, so it is actually preferable to assign to items ofos.environ. This also applies togetenv()andgetenvb(), which respectively useos.environandos.environbin their implementations.See also the
os.reload_environ()function.Note
On some platforms, including FreeBSD and macOS, setting
environmay cause memory leaks. Refer to the system documentation forputenv().Raises an auditing event
os.putenvwith argumentskey,value.Changed in version 3.9: The function is now always available.
- os.setegid(egid, /)¶
Set the current process’s effective group id.
Availability: Unix, not WASI, not Android.
- os.seteuid(euid, /)¶
Set the current process’s effective user id.
Availability: Unix, not WASI, not Android.
- os.setgid(gid, /)¶
Set the current process’ group id.
Availability: Unix, not WASI, not Android.
- os.setgroups(groups, /)¶
Set the list of supplemental group ids associated with the current process to groups. groups must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser.
Availability: Unix, not WASI.
Note
On macOS, the length of groups may not exceed the system-defined maximum number of effective group ids, typically 16. See the documentation for
getgroups()for cases where it may not return the same group list set by calling setgroups().
- os.setns(fd, nstype=0)¶
Reassociate the current thread with a Linux namespace. See the setns(2) and namespaces(7) man pages for more details.
If fd refers to a
/proc/pid/ns/link,setns()reassociates the calling thread with the namespace associated with that link, and nstype may be set to one of the CLONE_NEW* constants to impose constraints on the operation (0means no constraints).Since Linux 5.8, fd may refer to a PID file descriptor obtained from
pidfd_open(). In this case,setns()reassociates the calling thread into one or more of the same namespaces as the thread referred to by fd. This is subject to any constraints imposed by nstype, which is a bit mask combining one or more of the CLONE_NEW* constants, e.g.setns(fd, os.CLONE_NEWUTS | os.CLONE_NEWPID). The caller’s memberships in unspecified namespaces are left unchanged.fd can be any object with a
fileno()method, or a raw file descriptor.This example reassociates the thread with the
initprocess’s network namespace:fd = os.open("/proc/1/ns/net", os.O_RDONLY) os.setns(fd, os.CLONE_NEWNET) os.close(fd)
Availability: Linux >= 3.0 with glibc >= 2.14.
Added in version 3.12.
See also
The
unshare()function.
- os.setpgrp()¶
Call the system call
setpgrp()orsetpgrp(0, 0)depending on which version is implemented (if any). See the Unix manual for the semantics.Availability: Unix, not WASI.
- os.setpgid(pid, pgrp, /)¶
Call the system call
setpgid()to set the process group id of the process with id pid to the process group with id pgrp. See the Unix manual for the semantics.Availability: Unix, not WASI.
- os.setpriority(which, who, priority)¶
Set program scheduling priority. The value which is one of
PRIO_PROCESS,PRIO_PGRP, orPRIO_USER, and who is interpreted relative to which (a process identifier forPRIO_PROCESS, process group identifier forPRIO_PGRP, and a user ID forPRIO_USER). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process. priority is a value in the range -20 to 19. The default priority is 0; lower priorities cause more favorable scheduling.Availability: Unix, not WASI.
Added in version 3.3.
- os.setregid(rgid, egid, /)¶
Set the current process’s real and effective group ids.
Availability: Unix, not WASI, not Android.
- os.setresgid(rgid, egid, sgid, /)¶
Set the current process’s real, effective, and saved group ids.
Availability: Unix, not WASI, not Android.
Added in version 3.2.
- os.setresuid(ruid, euid, suid, /)¶
Set the current process’s real, effective, and saved user ids.
Availability: Unix, not WASI, not Android.
Added in version 3.2.
- os.setreuid(ruid, euid, /)¶
Set the current process’s real and effective user ids.
Availability: Unix, not WASI, not Android.
- os.getsid(pid, /)¶
Call the system call
getsid(). See the Unix manual for the semantics.Availability: Unix, not WASI.
- os.setsid()¶
Call the system call
setsid(). See the Unix manual for the semantics.Availability: Unix, not WASI.
- os.setuid(uid, /)¶
Set the current process’s user id.
Availability: Unix, not WASI, not Android.
- os.strerror(code, /)¶
Return the error message corresponding to the error code in code. On platforms where
strerror()returnsNULLwhen given an unknown error number,ValueErroris raised.
- os.supports_bytes_environ¶
Trueif the native OS type of the environment is bytes (eg.Falseon Windows).Added in version 3.2.
- os.umask(mask, /)¶
Set the current numeric umask and return the previous umask.
The function is a stub on WASI, see WebAssembly platforms for more information.
- os.uname()¶
Returns information identifying the current operating system. The return value is an object with five attributes:
sysname- operating system namenodename- name of machine on network (implementation-defined)release- operating system releaseversion- operating system versionmachine- hardware identifier
For backwards compatibility, this object is also iterable, behaving like a five-tuple containing
sysname,nodename,release,version, andmachinein that order.Some systems truncate
nodenameto 8 characters or to the leading component; a better way to get the hostname issocket.gethostname()or evensocket.gethostbyaddr(socket.gethostname()).On macOS, iOS and Android, this returns the kernel name and version (i.e.,
'Darwin'on macOS and iOS;'Linux'on Android).platform.uname()can be used to get the user-facing operating system name and version on iOS and Android.Availability: Unix.
Changed in version 3.3: Return type changed from a tuple to a tuple-like object with named attributes.
- os.unsetenv(key, /)¶
Unset (delete) the environment variable named key. Such changes to the environment affect subprocesses started with
os.system(),popen()orfork()andexecv().Deletion of items in
os.environis automatically translated into a corresponding call tounsetenv(); however, calls tounsetenv()don’t updateos.environ, so it is actually preferable to delete items ofos.environ.See also the
os.reload_environ()function.Raises an auditing event
os.unsetenvwith argumentkey.Changed in version 3.9: The function is now always available and is also available on Windows.
Disassociate parts of the process execution context, and move them into a newly created namespace. See the unshare(2) man page for more details. The flags argument is a bit mask, combining zero or more of the CLONE_* constants, that specifies which parts of the execution context should be unshared from their existing associations and moved to a new namespace. If the flags argument is
0, no changes are made to the calling process’s execution context.Availability: Linux >= 2.6.16.
Added in version 3.12.
See also
The
setns()function.
File Object Creation¶
These functions create new file objects. (See also
open() for opening file descriptors.)
File Descriptor Operations¶
These functions operate on I/O streams referenced using file descriptors.
File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth. The name “file descriptor” is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors.
The fileno() method can be used to obtain the file descriptor
associated with a file object when required. Note that using the file
descriptor directly will bypass the file object methods, ignoring aspects such
as internal buffering of data.
- os.close(fd)¶
Close file descriptor fd.
- os.closerange(fd_low, fd_high, /)¶
Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. Equivalent to (but much faster than):
for fd in range(fd_low, fd_high): try: os.close(fd) except OSError: pass
- os.copy_file_range(src, dst, count, offset_src=None, offset_dst=None)¶
Copy count bytes from file descriptor src, starting from offset offset_src, to file descriptor dst, starting from offset offset_dst. If offset_src is
None, then src is read from the current position; respectively for offset_dst.In Linux kernel older than 5.3, the files pointed to by src and dst must reside in the same filesystem, otherwise an
OSErroris raised witherrnoset toerrno.EXDEV.This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel. Additionally, some filesystems could implement extra optimizations, such as the use of reflinks (i.e., two or more inodes that share pointers to the same copy-on-write disk blocks; supported file systems include btrfs and XFS) and server-side copy (in the case of NFS).
The function copies bytes between two file descriptors. Text options, like the encoding and the line ending, are ignored.
The return value is the amount of bytes copied. This could be less than the amount requested.
Note
On Linux,
os.copy_file_range()should not be used for copying a range of a pseudo file from a special filesystem like procfs and sysfs. It will always copy no bytes and return 0 as if the file was empty because of a known Linux kernel issue.Availability: Linux >= 4.5 with glibc >= 2.27.
Added in version 3.8.
- os.device_encoding(fd)¶
Return a string describing the encoding of the device associated with fd if it is connected to a terminal; else return
None.On Unix, if the Python UTF-8 Mode is enabled, return
'UTF-8'rather than the device encoding.Changed in version 3.10: On Unix, the function now implements the Python UTF-8 Mode.
- os.dup(fd, /)¶
Return a duplicate of file descriptor fd. The new file descriptor is non-inheritable.
On Windows, when duplicating a standard stream (0: stdin, 1: stdout, 2: stderr), the new file descriptor is inheritable.
Availability: not WASI.
Changed in version 3.4: The new file descriptor is now non-inheritable.
- os.dup2(fd, fd2, inheritable=True)¶
Duplicate file descriptor fd to fd2, closing the latter first if necessary. Return fd2. The new file descriptor is inheritable by default or non-inheritable if inheritable is
False.Availability: not WASI.
Changed in version 3.4: Add the optional inheritable parameter.
Changed in version 3.7: Return fd2 on success. Previously,
Nonewas always returned.
- os.fchmod(fd, mode)¶
Change the mode of the file given by fd to the numeric mode. See the docs for
chmod()for possible values of mode. As of Python 3.3, this is equivalent toos.chmod(fd, mode).Raises an auditing event
os.chmodwith argumentspath,mode,dir_fd.Availability: Unix, Windows.
The function is limited on WASI, see WebAssembly platforms for more information.
Changed in version 3.13: Added support on Windows.
- os.fchown(fd, uid, gid)¶
Change the owner and group id of the file given by fd to the numeric uid and gid. To leave one of the ids unchanged, set it to -1. See
chown(). As of Python 3.3, this is equivalent toos.chown(fd, uid, gid).Raises an auditing event
os.chownwith argumentspath,uid,gid,dir_fd.Availability: Unix.
The function is limited on WASI, see WebAssembly platforms for more information.
- os.fdatasync(fd)¶
Force write of file with filedescriptor fd to disk. Does not force update of metadata.
Availability: Unix.
Note
This function is not available on MacOS.
- os.fpathconf(fd, name, /)¶
Return system configuration information relevant to an open file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the
pathconf_namesdictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.If name is a string and is not known,
ValueErroris raised. If a specific value for name is not supported by the host system, even if it is included inpathconf_names, anOSErroris raised witherrno.EINVALfor the error number.As of Python 3.3, this is equivalent to
os.pathconf(fd, name).Availability: Unix.
- os.fstat(fd)¶
Get the status of the file descriptor fd. Return a
stat_resultobject.As of Python 3.3, this is equivalent to
os.stat(fd).See also
The
stat()function.
- os.fstatvfs(fd, /)¶
Return information about the filesystem containing the file associated with file descriptor fd, like
statvfs(). As of Python 3.3, this is equivalent toos.statvfs(fd).Availability: Unix.
- os.fsync(fd)¶
Force write of file with filedescriptor fd to disk. On Unix, this calls the native
fsync()function; on Windows, the MS_commit()function.If you’re starting with a buffered Python file object f, first do
f.flush(), and then doos.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.Availability: Unix, Windows.
- os.ftruncate(fd, length, /)¶
Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size. As of Python 3.3, this is equivalent to
os.truncate(fd, length).Raises an auditing event
os.truncatewith argumentsfd,length.Availability: Unix, Windows.
Changed in version 3.5: Added support for Windows
- os.get_blocking(fd, /)¶
Get the blocking mode of the file descriptor:
Falseif theO_NONBLOCKflag is set,Trueif the flag is cleared.See also
set_blocking()andsocket.socket.setblocking().Availability: Unix, Windows.
The function is limited on WASI, see WebAssembly platforms for more information.
On Windows, this function is limited to pipes.
Added in version 3.5.
Changed in version 3.12: Added support for pipes on Windows.
- os.grantpt(fd, /)¶
Grant access to the slave pseudo-terminal device associated with the master pseudo-terminal device to which the file descriptor fd refers. The file descriptor fd is not closed upon failure.
Calls the C standard library function
grantpt().Availability: Unix, not WASI.
Added in version 3.13.
- os.isatty(fd, /)¶
Return
Trueif the file descriptor fd is open and connected to a tty(-like) device, elseFalse.
- os.lockf(fd, cmd, len, /)¶
Apply, test or remove a POSIX lock on an open file descriptor. fd is an open file descriptor. cmd specifies the command to use - one of
F_LOCK,F_TLOCK,F_ULOCKorF_TEST. len specifies the section of the file to lock.Raises an auditing event
os.lockfwith argumentsfd,cmd,len.Availability: Unix.
Added in version 3.3.
- os.F_LOCK¶
- os.F_TLOCK¶
- os.F_ULOCK¶
- os.F_TEST¶
Flags that specify what action
lockf()will take.Availability: Unix.
Added in version 3.3.
- os.login_tty(fd, /)¶
Prepare the tty of which fd is a file descriptor for a new login session. Make the calling process a session leader; make the tty the controlling tty, the stdin, the stdout, and the stderr of the calling process; close fd.
Availability: Unix, not WASI.
Added in version 3.11.
- os.lseek(fd, pos, whence, /)¶
Set the current position of file descriptor fd to position pos, modified by whence, and return the new position in bytes relative to the start of the file. Valid values for whence are:
SEEK_SETor0– set pos relative to the beginning of the fileSEEK_CURor1– set pos relative to the current file positionSEEK_ENDor2– set pos relative to the end of the fileSEEK_HOLE– set pos to the next data location, relative to posSEEK_DATA– set pos to the next data hole, relative to pos
Changed in version 3.3: Add support for
SEEK_HOLEandSEEK_DATA.
- os.SEEK_SET¶
- os.SEEK_CUR¶
- os.SEEK_END¶
Parameters to the
lseek()function and theseek()method on file-like objects, for whence to adjust the file position indicator.SEEK_SETAdjust the file position relative to the beginning of the file.
SEEK_CURAdjust the file position relative to the current file position.
SEEK_ENDAdjust the file position relative to the end of the file.
Their values are 0, 1, and 2, respectively.
- os.SEEK_HOLE¶
- os.SEEK_DATA¶
Parameters to the
lseek()function and theseek()method on file-like objects, for seeking file data and holes on sparsely allocated files.SEEK_DATAAdjust the file offset to the next location containing data, relative to the seek position.
SEEK_HOLEAdjust the file offset to the next location containing a hole, relative to the seek position. A hole is defined as a sequence of zeros.
Note
These operations only make sense for filesystems that support them.
Availability: Linux >= 3.1, macOS, Unix
Added in version 3.3.
- os.open(path, flags, mode=0o777, *, dir_fd=None)¶
Open the file path and set various flags according to flags and possibly its mode according to mode. When computing mode, the current umask value is first masked out. Return the file descriptor for the newly opened file. The new file descriptor is non-inheritable.
For a description of the flag and mode values, see the C run-time documentation; flag constants (like
O_RDONLYandO_WRONLY) are defined in theosmodule. In particular, on Windows addingO_BINARYis needed to open files in binary mode.This function can support paths relative to directory descriptors with the dir_fd parameter.
Raises an auditing event
openwith argumentspath,mode,flags.Changed in version 3.4: The new file descriptor is now non-inheritable.
Note
This function is intended for low-level I/O. For normal usage, use the built-in function
open(), which returns a file object withread()andwrite()methods (and many more). To wrap a file descriptor in a file object, usefdopen().Changed in version 3.3: Added the dir_fd parameter.
Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an
InterruptedErrorexception (see PEP 475 for the rationale).Changed in version 3.6: Accepts a path-like object.
The following constants are options for the flags parameter to the
open() function. They can be combined using the bitwise OR operator
|. Some of them are not available on all platforms. For descriptions of
their availability and use, consult the open(2) manual page on Unix
or the MSDN on Windows.
- os.O_RDONLY¶
- os.O_WRONLY¶
- os.O_RDWR¶
- os.O_APPEND¶
- os.O_CREAT¶
- os.O_EXCL¶
- os.O_TRUNC¶
The above constants are available on Unix and Windows.
- os.O_DSYNC¶
- os.O_RSYNC¶
- os.O_SYNC¶
- os.O_NDELAY¶
- os.O_NONBLOCK¶
- os.O_NOCTTY¶
- os.O_CLOEXEC¶
The above constants are only available on Unix.
Changed in version 3.3: Add
O_CLOEXECconstant.
- os.O_BINARY¶
- os.O_NOINHERIT¶
- os.O_SHORT_LIVED¶
- os.O_TEMPORARY¶
- os.O_RANDOM¶
- os.O_SEQUENTIAL¶
- os.O_TEXT¶
The above constants are only available on Windows.
- os.O_EVTONLY¶
- os.O_FSYNC¶
- os.O_SYMLINK¶
- os.O_NOFOLLOW_ANY¶
The above constants are only available on macOS.
Changed in version 3.10: Add
O_EVTONLY,O_FSYNC,O_SYMLINKandO_NOFOLLOW_ANYconstants.
- os.O_ASYNC¶
- os.O_DIRECT¶
- os.O_DIRECTORY¶
- os.O_NOFOLLOW¶
- os.O_NOATIME¶
- os.O_PATH¶
- os.O_TMPFILE¶
- os.O_SHLOCK¶
- os.O_EXLOCK¶
The above constants are extensions and not present if they are not defined by the C library.
- os.openpty()¶
Open a new pseudo-terminal pair. Return a pair of file descriptors
(master, slave)for the pty and the tty, respectively. The new file descriptors are non-inheritable. For a (slightly) more portable approach, use theptymodule.Availability: Unix, not WASI.
Changed in version 3.4: The new file descriptors are now non-inheritable.
- os.pipe()¶
Create a pipe. Return a pair of file descriptors
(r, w)usable for reading and writing, respectively. The new file descriptor is non-inheritable.Availability: Unix, Windows.
Changed in version 3.4: The new file descriptors are now non-inheritable.
- os.pipe2(flags, /)¶
Create a pipe with flags set atomically. flags can be constructed by ORing together one or more of these values:
O_NONBLOCK,O_CLOEXEC. Return a pair of file descriptors(r, w)usable for reading and writing, respectively.Availability: Unix, not WASI.
Added in version 3.3.
- os.posix_fallocate(fd, offset, len, /)¶
Ensures that enough disk space is allocated for the file specified by fd starting from offset and continuing for len bytes.
Availability: Unix.
Added in version 3.3.
- os.posix_fadvise(fd, offset, len, advice, /)¶
Announces an intention to access data in a specific pattern thus allowing the kernel to make optimizations. The advice applies to the region of the file specified by fd starting at offset and continuing for len bytes. advice is one of
POSIX_FADV_NORMAL,POSIX_FADV_SEQUENTIAL,POSIX_FADV_RANDOM,POSIX_FADV_NOREUSE,POSIX_FADV_WILLNEEDorPOSIX_FADV_DONTNEED.Availability: Unix.
Added in version 3.3.
- os.POSIX_FADV_NORMAL¶
- os.POSIX_FADV_SEQUENTIAL¶
- os.POSIX_FADV_RANDOM¶
- os.POSIX_FADV_NOREUSE¶
- os.POSIX_FADV_WILLNEED¶
- os.POSIX_FADV_DONTNEED¶
Flags that can be used in advice in
posix_fadvise()that specify the access pattern that is likely to be used.Availability: Unix.
Added in version 3.3.
- os.pread(fd, n, offset, /)¶
Read at most n bytes from file descriptor fd at a position of offset, leaving the file offset unchanged.
Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned.
Availability: Unix.
Added in version 3.3.
- os.posix_openpt(oflag, /)¶
Open and return a file descriptor for a master pseudo-terminal device.
Calls the C standard library function
posix_openpt(). The oflag argument is used to set file status flags and file access modes as specified in the manual page ofposix_openpt()of your system.The returned file descriptor is non-inheritable. If the value
O_CLOEXECis available on the system, it is added to oflag.Availability: Unix, not WASI.
Added in version 3.13.
- os.preadv(fd, buffers, offset, flags=0, /)¶
Read from a file descriptor fd at a position of offset into mutable bytes-like objects buffers, leaving the file offset unchanged. Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.
The flags argument contains a bitwise OR of zero or more of the following flags:
Return the total number of bytes actually read which can be less than the total capacity of all the objects.
The operating system may set a limit (
sysconf()value'SC_IOV_MAX') on the number of buffers that can be used.Combine the functionality of
os.readv()andos.pread().Availability: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.
Using flags requires Linux >= 4.6.
Added in version 3.7.
- os.RWF_NOWAIT¶
Do not wait for data which is not immediately available. If this flag is specified, the system call will return instantly if it would have to read data from the backing storage or wait for a lock.
If some data was successfully read, it will return the number of bytes read. If no bytes were read, it will return
-1and set errno toerrno.EAGAIN.Availability: Linux >= 4.14.
Added in version 3.7.
- os.RWF_HIPRI¶
High priority read/write. Allows block-based filesystems to use polling of the device, which provides lower latency, but may use additional resources.
Currently, on Linux, this feature is usable only on a file descriptor opened using the
O_DIRECTflag.Availability: Linux >= 4.6.
Added in version 3.7.
- os.ptsname(fd, /)¶
Return the name of the slave pseudo-terminal device associated with the master pseudo-terminal device to which the file descriptor fd refers. The file descriptor fd is not closed upon failure.
Calls the reentrant C standard library function
ptsname_r()if it is available; otherwise, the C standard library functionptsname(), which is not guaranteed to be thread-safe, is called.Availability: Unix, not WASI.
Added in version 3.13.
- os.pwrite(fd, str, offset, /)¶
Write the bytestring in str to file descriptor fd at position of offset, leaving the file offset unchanged.
Return the number of bytes actually written.
Availability: Unix.
Added in version 3.3.
- os.pwritev(fd, buffers, offset, flags=0, /)¶
Write the buffers contents to file descriptor fd at an offset offset, leaving the file offset unchanged. buffers must be a sequence of bytes-like objects. Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.
The flags argument contains a bitwise OR of zero or more of the following flags:
Return the total number of bytes actually written.
The operating system may set a limit (
sysconf()value'SC_IOV_MAX') on the number of buffers that can be used.Combine the functionality of
os.writev()andos.pwrite().Availability: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.
Using flags requires Linux >= 4.6.
Added in version 3.7.
- os.RWF_DSYNC¶
Provide a per-write equivalent of the
O_DSYNCos.open()flag. This flag effect applies only to the data range written by the system call.Availability: Linux >= 4.7.
Added in version 3.7.
- os.RWF_SYNC¶
Provide a per-write equivalent of the
O_SYNCos.open()flag. This flag effect applies only to the data range written by the system call.Availability: Linux >= 4.7.
Added in version 3.7.
- os.RWF_APPEND¶
Provide a per-write equivalent of the
O_APPENDos.open()flag. This flag is meaningful only foros.pwritev(), and its effect applies only to the data range written by the system call. The offset argument does not affect the write operation; the data is always appended to the end of the file. However, if the offset argument is-1, the current file offset is updated.Availability: Linux >= 4.16.
Added in version 3.10.
- os.read(fd, n, /)¶
Read at most n bytes from file descriptor fd.
Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned.
Note
This function is intended for low-level I/O and must be applied to a file descriptor as returned by
os.open()orpipe(). To read a “file object” returned by the built-in functionopen()or bypopen()orfdopen(), orsys.stdin, use itsread()orreadline()methods.Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an
InterruptedErrorexception (see PEP 475 for the rationale).
- os.readinto(fd, buffer, /)¶
Read from a file descriptor fd into a mutable buffer object buffer.
The buffer should be mutable and bytes-like. On success, returns the number of bytes read. Less bytes may be read than the size of the buffer. The underlying system call will be retried when interrupted by a signal, unless the signal handler raises an exception. Other errors will not be retried and an error will be raised.
Returns 0 if fd is at end of file or if the provided buffer has length 0 (which can be used to check for errors without reading data). Never returns negative.
Note
This function is intended for low-level I/O and must be applied to a file descriptor as returned by
os.open()oros.pipe(). To read a “file object” returned by the built-in functionopen(), orsys.stdin, use its member functions, for exampleio.BufferedIOBase.readinto(),io.BufferedIOBase.read(), orio.TextIOBase.read()Added in version 3.14.
- os.sendfile(out_fd, in_fd, offset, count)¶
- os.sendfile(out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0)
Copy count bytes from file descriptor in_fd to file descriptor out_fd starting at offset. Return the number of bytes sent. When EOF is reached return
0.The first function notation is supported by all platforms that define
sendfile().On Linux, if offset is given as
None, the bytes are read from the current position of in_fd and the position of in_fd is updated.The second case may be used on macOS and FreeBSD where headers and trailers are arbitrary sequences of buffers that are written before and after the data from in_fd is written. It returns the same as the first case.
On macOS and FreeBSD, a value of
0for count specifies to send until the end of in_fd is reached.All platforms support sockets as out_fd file descriptor, and some platforms allow other types (e.g. regular file, pipe) as well.
Cross-platform applications should not use headers, trailers and flags arguments.
Availability: Unix, not WASI.
Note
For a higher-level wrapper of
sendfile(), seesocket.socket.sendfile().Added in version 3.3.
Changed in version 3.9: Parameters out and in was renamed to out_fd and in_fd.
- os.SF_NODISKIO¶
- os.SF_MNOWAIT¶
- os.SF_SYNC¶
Parameters to the
sendfile()function, if the implementation supports them.Availability: Unix, not WASI.
Added in version 3.3.
- os.SF_NOCACHE¶
Parameter to the
sendfile()function, if the implementation supports it. The data won’t be cached in the virtual memory and will be freed afterwards.Availability: Unix, not WASI.
Added in version 3.11.
- os.set_blocking(fd, blocking, /)¶
Set the blocking mode of the specified file descriptor. Set the
O_NONBLOCKflag if blocking isFalse, clear the flag otherwise.See also
get_blocking()andsocket.socket.setblocking().Availability: Unix, Windows.
The function is limited on WASI, see WebAssembly platforms for more information.
On Windows, this function is limited to pipes.
Added in version 3.5.
Changed in version 3.12: Added support for pipes on Windows.
- os.splice(src, dst, count, offset_src=None, offset_dst=None, flags=0)¶
Transfer count bytes from file descriptor src, starting from offset offset_src, to file descriptor dst, starting from offset offset_dst.
The splicing behaviour can be modified by specifying a flags value. Any of the following variables may used, combined using bitwise OR (the
|operator):If
SPLICE_F_MOVEis specified, the kernel is asked to move pages instead of copying, but pages may still be copied if the kernel cannot move the pages from the pipe.If
SPLICE_F_NONBLOCKis specified, the kernel is asked to not block on I/O. This makes the splice pipe operations nonblocking, but splice may nevertheless block because the spliced file descriptors may block.If
SPLICE_F_MOREis specified, it hints to the kernel that more data will be coming in a subsequent splice.
At least one of the file descriptors must refer to a pipe. If offset_src is
None, then src is read from the current position; respectively for offset_dst. The offset associated to the file descriptor that refers to a pipe must beNone. The files pointed to by src and dst must reside in the same filesystem, otherwise anOSErroris raised witherrnoset toerrno.EXDEV.This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel. Additionally, some filesystems could implement extra optimizations. The copy is done as if both files are opened as binary.
Upon successful completion, returns the number of bytes spliced to or from the pipe. A return value of 0 means end of input. If src refers to a pipe, then this means that there was no data to transfer, and it would not make sense to block because there are no writers connected to the write end of the pipe.
See also
The splice(2) man page.
Availability: Linux >= 2.6.17 with glibc >= 2.5
Added in version 3.10.
- os.readv(fd, buffers, /)¶
Read from a file descriptor fd into a number of mutable bytes-like objects buffers. Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.
Return the total number of bytes actually read which can be less than the total capacity of all the objects.
The operating system may set a limit (
sysconf()value'SC_IOV_MAX') on the number of buffers that can be used.Availability: Unix.
Added in version 3.3.
- os.tcgetpgrp(fd, /)¶
Return the process group associated with the terminal given by fd (an open file descriptor as returned by
os.open()).Availability: Unix, not WASI.
- os.tcsetpgrp(fd, pg, /)¶
Set the process group associated with the terminal given by fd (an open file descriptor as returned by
os.open()) to pg.Availability: Unix, not WASI.
- os.ttyname(fd, /)¶
Return a string which specifies the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised.
Availability: Unix.
- os.unlockpt(fd, /)¶
Unlock the slave pseudo-terminal device associated with the master pseudo-terminal device to which the file descriptor fd refers. The file descriptor fd is not closed upon failure.
Calls the C standard library function
unlockpt().Availability: Unix, not WASI.
Added in version 3.13.
- os.write(fd, str, /)¶
Write the bytestring in str to file descriptor fd.
Return the number of bytes actually written.
Note
This function is intended for low-level I/O and must be applied to a file descriptor as returned by
os.open()orpipe(). To write a “file object” returned by the built-in functionopen()or bypopen()orfdopen(), orsys.stdoutorsys.stderr, use itswrite()method.Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an
InterruptedErrorexception (see PEP 475 for the rationale).
- os.writev(fd, buffers, /)¶
Write the contents of buffers to file descriptor fd. buffers must be a sequence of bytes-like objects. Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.
Returns the total number of bytes actually written.
The operating system may set a limit (
sysconf()value'SC_IOV_MAX') on the number of buffers that can be used.Availability: Unix.
Added in version 3.3.
Querying the size of a terminal¶
Added in version 3.3.
- os.get_terminal_size(fd=STDOUT_FILENO, /)¶
Return the size of the terminal window as
(columns, lines), tuple of typeterminal_size.The optional argument
fd(defaultSTDOUT_FILENO, or standard output) specifies which file descriptor should be queried.If the file descriptor is not connected to a terminal, an
OSErroris raised.shutil.get_terminal_size()is the high-level function which should normally be used,os.get_terminal_sizeis the low-level implementation.Availability: Unix, Windows.
Inheritance of File Descriptors¶
Added in version 3.4.
A file descriptor has an “inheritable” flag which indicates if the file descriptor can be inherited by child processes. Since Python 3.4, file descriptors created by Python are non-inheritable by default.
On UNIX, non-inheritable file descriptors are closed in child processes at the execution of a new program, other file descriptors are inherited.
On Windows, non-inheritable handles and file descriptors are closed in child
processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout
and stderr), which are always inherited. Using spawn* functions,
all inheritable handles and all inheritable file descriptors are inherited.
Using the subprocess module, all file descriptors except standard
streams are closed, and inheritable handles are only inherited if the
close_fds parameter is False.
On WebAssembly platforms, the file descriptor cannot be modified.
- os.get_inheritable(fd, /)¶
Get the “inheritable” flag of the specified file descriptor (a boolean).
- os.set_inheritable(fd, inheritable, /)¶
Set the “inheritable” flag of the specified file descriptor.
- os.get_handle_inheritable(handle, /)¶
Get the “inheritable” flag of the specified handle (a boolean).
Availability: Windows.
- os.set_handle_inheritable(handle, inheritable, /)¶
Set the “inheritable” flag of the specified handle.
Availability: Windows.
Files and Directories¶
On some Unix platforms, many of these functions support one or more of these features:
specifying a file descriptor: Normally the path argument provided to functions in the
osmodule must be a string specifying a file path. However, some functions now alternatively accept an open file descriptor for their path argument. The function will then operate on the file referred to by the descriptor. For POSIX systems, Python will call the variant of the function prefixed withf(e.g. callfchdirinstead ofchdir).You can check whether or not path can be specified as a file descriptor for a particular function on your platform using
os.supports_fd. If this functionality is unavailable, using it will raise aNotImplementedError.If the function also supports dir_fd or follow_symlinks arguments, it’s an error to specify one of those when supplying path as a file descriptor.
paths relative to directory descriptors: If dir_fd is not
None, it should be a file descriptor referring to a directory, and the path to operate on should be relative; path will then be relative to that directory. If the path is absolute, dir_fd is ignored. For POSIX systems, Python will call the variant of the function with anatsuffix and possibly prefixed withf(e.g. callfaccessatinstead ofaccess).You can check whether or not dir_fd is supported for a particular function on your platform using
os.supports_dir_fd. If it’s unavailable, using it will raise aNotImplementedError.
not following symlinks: If follow_symlinks is
False, and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself rather than the file pointed to by the link. For POSIX systems, Python will call thel...variant of the function.You can check whether or not follow_symlinks is supported for a particular function on your platform using
os.supports_follow_symlinks. If it’s unavailable, using it will raise aNotImplementedError.
- os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)¶
Use the real uid/gid to test for access to path. Note that most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path. mode should be
F_OKto test the existence of path, or it can be the inclusive OR of one or more ofR_OK,W_OK, andX_OKto test permissions. ReturnTrueif access is allowed,Falseif not. See the Unix man page access(2) for more information.This function can support specifying paths relative to directory descriptors and not following symlinks.
If effective_ids is
True,access()will perform its access checks using the effective uid/gid instead of the real uid/gid. effective_ids may not be supported on your platform; you can check whether or not it is available usingos.supports_effective_ids. If it is unavailable, using it will raise aNotImplementedError.Note
Using
access()to check if a user is authorized to e.g. open a file before actually doing so usingopen()creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example:if os.access("myfile", os.R_OK): with open("myfile") as fp: return fp.read() return "some default data"
is better written as:
try: fp = open("myfile") except PermissionError: return "some default data" else: with fp: return fp.read()
Note
I/O operations may fail even when
access()indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.Changed in version 3.3: Added the dir_fd, effective_ids, and follow_symlinks parameters.
Changed in version 3.6: Accepts a path-like object.
- os.F_OK¶
- os.R_OK¶
- os.W_OK¶
- os.X_OK¶
Values to pass as the mode parameter of
access()to test the existence, readability, writability and executability of path, respectively.
- os.chdir(path)¶
Change the current working directory to path.
This function can support specifying a file descriptor. The descriptor must refer to an opened directory, not an open file.
This function can raise
OSErrorand subclasses such asFileNotFoundError,PermissionError, andNotADirectoryError.Raises an auditing event
os.chdirwith argumentpath.Changed in version 3.3: Added support for specifying path as a file descriptor on some platforms.
Changed in version 3.6: Accepts a path-like object.
- os.chflags(path, flags, *, follow_symlinks=True)¶
Set the flags of path to the numeric flags. flags may take a combination (bitwise OR) of the following values (as defined in the
statmodule):This function can support not following symlinks.
Raises an auditing event
os.chflagswith argumentspath,flags.Availability: Unix, not WASI.
Changed in version 3.3: Added the follow_symlinks parameter.
Changed in version 3.6: Accepts a path-like object.
- os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)¶
Change the mode of path to the numeric mode. mode may take one of the following values (as defined in the
statmodule) or bitwise ORed combinations of them:This function can support specifying a file descriptor, paths relative to directory descriptors and not following symlinks.
Note
Although Windows supports
chmod(), you can only set the file’s read-only flag with it (via thestat.S_IWRITEandstat.S_IREADconstants or a corresponding integer value). All other bits are ignored. The default value of follow_symlinks isFalseon Windows.The function is limited on WASI, see WebAssembly platforms for more information.
Raises an auditing event
os.chmodwith argumentspath,mode,dir_fd.Changed in version 3.3: Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments.
Changed in version 3.6: Accepts a path-like object.
Changed in version 3.13: Added support for a file descriptor and the follow_symlinks argument on Windows.
- os.chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)¶
Change the owner and group id of path to the numeric uid and gid. To leave one of the ids unchanged, set it to -1.
This function can support specifying a file descriptor, paths relative to directory descriptors and not following symlinks.
See
shutil.chown()for a higher-level function that accepts names in addition to numeric ids.Raises an auditing event
os.chownwith argumentspath,uid,gid,dir_fd.Availability: Unix.
The function is limited on WASI, see WebAssembly platforms for more information.
Changed in version 3.3: Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments.
Changed in version 3.6: Supports a path-like object.
- os.chroot(path)¶
Change the root directory of the current process to path.
Availability: Unix, not WASI, not Android.
Changed in version 3.6: Accepts a path-like object.
- os.fchdir(fd)¶
Change the current working directory to the directory represented by the file descriptor fd. The descriptor must refer to an opened directory, not an open file. As of Python 3.3, this is equivalent to
os.chdir(fd).Raises an auditing event
os.chdirwith argumentpath.Availability: Unix.
- os.getcwd()¶
Return a string representing the current working directory.
- os.getcwdb()¶
Return a bytestring representing the current working directory.
Changed in version 3.8: The function now uses the UTF-8 encoding on Windows, rather than the ANSI code page: see PEP 529 for the rationale. The function is no longer deprecated on Windows.
- os.lchflags(path, flags)¶
Set the flags of path to the numeric flags, like
chflags(), but do not follow symbolic links. As of Python 3.3, this is equivalent toos.chflags(path, flags, follow_symlinks=False).Raises an auditing event
os.chflagswith argumentspath,flags.Availability: Unix, not WASI.
Changed in version 3.6: Accepts a path-like object.
- os.lchmod(path, mode)¶
Change the mode of path to the numeric mode. If path is a symlink, this affects the symlink rather than the target. See the docs for
chmod()for possible values of mode. As of Python 3.3, this is equivalent toos.chmod(path, mode, follow_symlinks=False).lchmod()is not part of POSIX, but Unix implementations may have it if changing the mode of symbolic links is supported.Raises an auditing event
os.chmodwith argumentspath,mode,dir_fd.Availability: Unix, Windows, not Linux, FreeBSD >= 1.3, NetBSD >= 1.3, not OpenBSD
Changed in version 3.6: Accepts a path-like object.
Changed in version 3.13: Added support on Windows.
- os.lchown(path, uid, gid)¶
Change the owner and group id of path to the numeric uid and gid. This function will not follow symbolic links. As of Python 3.3, this is equivalent to
os.chown(path, uid, gid, follow_symlinks=False).Raises an auditing event
os.chownwith argumentspath,uid,gid,dir_fd.Availability: Unix.
Changed in version 3.6: Accepts a path-like object.
- os.link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)¶
Create a hard link pointing to src named dst.
This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors, and not following symlinks. The default value of follow_symlinks is
Falseon Windows.Raises an auditing event
os.linkwith argumentssrc,dst,src_dir_fd,dst_dir_fd.Availability: Unix, Windows.
Changed in version 3.2: Added Windows support.
Changed in version 3.3: Added the src_dir_fd, dst_dir_fd, and follow_symlinks parameters.
Changed in version 3.6: Accepts a path-like object for src and dst.
- os.listdir(path='.')¶
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries
'.'and'..'even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.path may be a path-like object. If path is of type
bytes(directly or indirectly through thePathLikeinterface), the filenames returned will also be of typebytes; in all other circumstances, they will be of typestr.This function can also support specifying a file descriptor; the file descriptor must refer to a directory.
Raises an auditing event
os.listdirwith argumentpath.Note
To encode
strfilenames tobytes, usefsencode().See also
The
scandir()function returns directory entries along with file attribute information, giving better performance for many common use cases.Changed in version 3.2: The path parameter became optional.
Changed in version 3.3: Added support for specifying path as an open file descriptor.
Changed in version 3.6: Accepts a path-like object.
- os.listdrives()¶
Return a list containing the names of drives on a Windows system.
A drive name typically looks like
'C:\\'. Not every drive name will be associated with a volume, and some may be inaccessible for a variety of reasons, including permissions, network connectivity or missing media. This function does not test for access.May raise
OSErrorif an error occurs collecting the drive names.Raises an auditing event
os.listdriveswith no arguments.Availability: Windows
Added in version 3.12.
- os.listmounts(volume)¶
Return a list containing the mount points for a volume on a Windows system.
volume must be represented as a GUID path, like those returned by
os.listvolumes(). Volumes may be mounted in multiple locations or not at all. In the latter case, the list will be empty. Mount points that are not associated with a volume will not be returned by this function.The mount points return by this function will be absolute paths, and may be longer than the drive name.
Raises
OSErrorif the volume is not recognized or if an error occurs collecting the paths.Raises an auditing event
os.listmountswith argumentvolume.Availability: Windows
Added in version 3.12.
- os.listvolumes()¶
Return a list containing the volumes in the system.
Volumes are typically represented as a GUID path that looks like
\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. Files can usually be accessed through a GUID path, permissions allowing. However, users are generally not familiar with them, and so the recommended use of this function is to retrieve mount points usingos.listmounts().May raise
OSErrorif an error occurs collecting the volumes.Raises an auditing event
os.listvolumeswith no arguments.Availability: Windows
Added in version 3.12.
- os.lstat(path, *, dir_fd=None)¶
Perform the equivalent of an
lstat()system call on the given path. Similar tostat(), but does not follow symbolic links. Return astat_resultobject.On platforms that do not support symbolic links, this is an alias for
stat().As of Python 3.3, this is equivalent to
os.stat(path, dir_fd=dir_fd, follow_symlinks=False).This function can also support paths relative to directory descriptors.
See also
The
stat()function.Changed in version 3.2: Added support for Windows 6.0 (Vista) symbolic links.
Changed in version 3.3: Added the dir_fd parameter.
Changed in version 3.6: Accepts a path-like object.
Changed in version 3.8: On Windows, now opens reparse points that represent another path (name surrogates), including symbolic links and directory junctions. Other kinds of reparse points are resolved by the operating system as for
stat().
- os.mkdir(path, mode=0o777, *, dir_fd=None)¶
Create a directory named path with numeric mode mode.
If the directory already exists,
FileExistsErroris raised. If a parent directory in the path does not exist,FileNotFoundErroris raised.On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If bits other than the last 9 (i.e. the last 3 digits of the octal representation of the mode) are set, their meaning is platform-dependent. On some platforms, they are ignored and you should call
chmod()explicitly to set them.On Windows, a mode of
0o700is specifically handled to apply access control to the new directory such that only the current user and administrators have access. Other values of mode are ignored.This function can also support paths relative to directory descriptors.
It is also possible to create temporary directories; see the
tempfilemodule’stempfile.mkdtemp()function.Raises an auditing event
os.mkdirwith argumentspath,mode,dir_fd.Changed in version 3.3: Added the dir_fd parameter.
Changed in version 3.6: Accepts a path-like object.
Changed in version 3.13: Windows now handles a mode of
0o700.
- os.makedirs(name, mode=0o777, exist_ok=False)¶
Recursive directory creation function. Like
mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.The mode parameter is passed to
mkdir()for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly created parent directories you can set the umask before invokingmakedirs(). The file permission bits of existing parent directories are not changed.If exist_ok is
False(the default), aFileExistsErroris raised if the target directory already exists.Note
makedirs()will become confused if the path elements to create includepardir(eg. “..” on UNIX systems).This function handles UNC paths correctly.
Raises an auditing event
os.mkdirwith argumentspath,mode,dir_fd.Changed in version 3.2: Added the exist_ok parameter.
Changed in version 3.4.1: Before Python 3.4.1, if exist_ok was
Trueand the directory existed,makedirs()would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082.Changed in version 3.6: Accepts a path-like object.
Changed in version 3.7: The mode argument no longer affects the file permission bits of newly created intermediate-level directories.
- os.mkfifo(path, mode=0o666, *, dir_fd=None)¶
Create a FIFO (a named pipe) named path with numeric mode mode. The current umask value is first masked out from the mode.
This function can also support paths relative to directory descriptors.
FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with
os.unlink()). Generally, FIFOs are used as rendezvous between “client” and “server” type processes: the server opens the FIFO for reading, and the client opens it for writing. Note thatmkfifo()doesn’t open the FIFO — it just creates the rendezvous point.Availability: Unix, not WASI.
Changed in version 3.3: Added the dir_fd parameter.
Changed in version 3.6: Accepts a path-like object.
- os.mknod(path, mode=0o600, device=0, *, dir_fd=None)¶
Create a filesystem node (file, device special file or named pipe) named path. mode specifies both the permissions to use and the type of node to be created, being combined (bitwise OR) with one of
stat.S_IFREG,stat.S_IFCHR,stat.S_IFBLK, andstat.S_IFIFO(those constants are available instat). Forstat.S_IFCHRandstat.S_IFBLK, device defines the newly created device special file (probably usingos.makedev()), otherwise it is ignored.This function can also support paths relative to directory descriptors.
Availability: Unix, not WASI.
Changed in version 3.3: Added the dir_fd parameter.
Changed in version 3.6: Accepts a path-like object.
- os.major(device, /)¶
Extract the device major number from a raw device number (usually the
st_devorst_rdevfield fromstat).
- os.minor(device, /)¶
Extract the device minor number from a raw device number (usually the
st_devorst_rdevfield fromstat).
- os.makedev(major, minor, /)¶
Compose a raw device number from the major and minor device numbers.
- os.pathconf(path, name)¶
Return system configuration information relevant to a named file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the
pathconf_namesdictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.If name is a string and is not known,
ValueErroris raised. If a specific value for name is not supported by the host system, even if it is included inpathconf_names, anOSErroris raised witherrno.EINVALfor the error number.This function can support specifying a file descriptor.
Availability: Unix.
Changed in version 3.6: Accepts a path-like object.
- os.pathconf_names¶
Dictionary mapping names accepted by
pathconf()andfpathconf()to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.Availability: Unix.
- os.readlink(path, *, dir_fd=None)¶
Return a string representing the path to which the symbolic link points. The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using
os.path.join(os.path.dirname(path), result).If the path is a string object (directly or indirectly through a
PathLikeinterface), the result will also be a string object, and the call may raise a UnicodeDecodeError. If the path is a bytes object (direct or indirectly), the result will be a bytes object.This function can also support paths relative to directory descriptors.
When trying to resolve a path that may contain links, use
realpath()to properly handle recursion and platform differences.Availability: Unix, Windows.
Changed in version 3.2: Added support for Windows 6.0 (Vista) symbolic links.
Changed in version 3.3: Added the dir_fd parameter.
Changed in version 3.6: Accepts a path-like object on Unix.
Changed in version 3.8: Accepts a path-like object and a bytes object on Windows.
Added support for directory junctions, and changed to return the substitution path (which typically includes
\\?\prefix) rather than the optional “print name” field that was previously returned.
- os.remove(path, *, dir_fd=None)¶
Remove (delete) the file path. If path is a directory, an
OSErroris raised. Usermdir()to remove directories. If the file does not exist, aFileNotFoundErroris raised.This function can support paths relative to directory descriptors.
On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.
This function is semantically identical to
unlink().Raises an auditing event
os.removewith argumentspath,dir_fd.Changed in version 3.3: Added the dir_fd parameter.
Changed in version 3.6: Accepts a path-like object.
- os.removedirs(name)¶
Remove directories recursively. Works like
rmdir()except that, if the leaf directory is successfully removed,removedirs()tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example,os.removedirs('foo/bar/baz')will first remove the directory'foo/bar/baz', and then remove'foo/bar'and'foo'if they are empty. RaisesOSErrorif the leaf directory could not be successfully removed.Raises an auditing event
os.removewith argumentspath,dir_fd.Changed in version 3.6: Accepts a path-like object.
- os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)¶
Rename the file or directory src to dst. If dst exists, the operation will fail with an
OSErrorsubclass in a number of cases:On Windows, if dst exists a
FileExistsErroris always raised. The operation may fail if src and dst are on different filesystems. Useshutil.move()to support moves to a different filesystem.On Unix, if src is a file and dst is a directory or vice-versa, an
IsADirectoryErroror aNotADirectoryErrorwill be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, anOSErroris raised. If both are files, dst will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors.
If you want cross-platform overwriting of the destination, use
replace().Raises an auditing event
os.renamewith argumentssrc,dst,src_dir_fd,dst_dir_fd.Changed in version 3.3: Added the src_dir_fd and dst_dir_fd parameters.
Changed in version 3.6: Accepts a path-like object for src and dst.
- os.renames(old, new)¶
Recursive directory or file renaming function. Works like
rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away usingremovedirs().Note
This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file.
Raises an auditing event
os.renamewith argumentssrc,dst,src_dir_fd,dst_dir_fd.Changed in version 3.6: Accepts a path-like object for old and new.
- os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)¶
Rename the file or directory src to dst. If dst is a non-empty directory,
OSErrorwill be raised. If dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors.
Raises an auditing event
os.renamewith argumentssrc,dst,src_dir_fd,dst_dir_fd.Added in version 3.3.
Changed in version 3.6: Accepts a path-like object for src and dst.
- os.rmdir(path, *, dir_fd=None)¶
Remove (delete) the directory path. If the directory does not exist or is not empty, a
FileNotFoundErroror anOSErroris raised respectively. In order to remove whole directory trees,shutil.rmtree()can be used.This function can support paths relative to directory descriptors.
Raises an auditing event
os.rmdirwith argumentspath,dir_fd.Changed in version 3.3: Added the dir_fd parameter.
Changed in version 3.6: Accepts a path-like object.
- os.scandir(path='.')¶
Return an iterator of
os.DirEntryobjects corresponding to the entries in the directory given by path. The entries are yielded in arbitrary order, and the special entries'.'and'..'are not included. If a file is removed from or added to the directory after creating the iterator, whether an entry for that file be included is unspecified.Using
scandir()instead oflistdir()can significantly increase the performance of code that also needs file type or file attribute information, becauseos.DirEntryobjects expose this information if the operating system provides it when scanning a directory. Allos.DirEntrymethods may perform a system call, butis_dir()andis_file()usually only require a system call for symbolic links;os.DirEntry.stat()always requires a system call on Unix but only requires one for symbolic links on Windows.path may be a path-like object. If path is of type
bytes(directly or indirectly through thePathLikeinterface), the type of thenameandpathattributes of eachos.DirEntrywill bebytes; in all other circumstances, they will be of typestr.This function can also support specifying a file descriptor; the file descriptor must refer to a directory.
Raises an auditing event
os.scandirwith argumentpath.The
scandir()iterator supports the