Search notes:

Python standard library: os

dir(os)

dir(os) finds the following «members» of os:
abc
abort()
access()
altsep
chdir() Changes the working directory to a given path or file descriptor. See also fchdir(), getcwd().
_check_methods()
chmod()
chown()
chroot()
CLD_CONTINUED
CLD_DUMPED
CLD_EXITED
CLD_KILLED
CLD_STOPPED
CLD_TRAPPED
close()
closerange()
confstr()
confstr_names
copy_file_range()
cpu_count()
ctermid() Filename of the controlling process's terminal (for example /dev/tty)
curdir
defpath
device_encoding()
devnull
DirEntry
dup()
dup2()
_Environ
environ
environb
error
EX_CANTCREAT
EX_CONFIG
EX_DATAERR
execl()
execle()
execlp()
execlpe()
execv()
execve()
execvp()
_execvpe()
execvpe()
EX_IOERR
_exists()
_exit() Exit the process with a given status and without calling cleanup handlers registered with atexit. The standard way to quit from a process is sys.exit(). os_exit() should normally be used in the child process after a fork().
EX_NOHOST
EX_NOINPUT
EX_NOPERM
EX_NOUSER
EX_OK
EX_OSERR
EX_OSFILE
EX_PROTOCOL
EX_SOFTWARE
EX_TEMPFAIL
extsep
EX_UNAVAILABLE
EX_USAGE
fchdir()
fchmod()
fchown()
fdatasync()
fdopen()
F_LOCK
F_OK
fork()
forkpty()
fpathconf()
fsdecode()
fsencode()
_fspath()
fspath()
fstat()
fstatvfs()
fsync()
F_TEST
F_TLOCK
ftruncate()
F_ULOCK
_fwalk()
fwalk()
GenericAlias
get_blocking()
getcwd()
getcwdb()
getegid()
getenv()
getenvb()
geteuid()
get_exec_path()
_get_exports_list()
getgid()
getgrouplist()
getgroups()
get_inheritable()
getloadavg()
getlogin()
getpgid()
getpgrp()
getpid()
getppid()
getpriority()
getrandom()
getresgid()
getresuid()
getsid()
get_terminal_size()
getuid()
getxattr()
GRND_NONBLOCK
GRND_RANDOM
initgroups()
isatty()
kill()
killpg()
lchown()
linesep
link()
listdir() The list of filenames found in the specified directory (default is '.'). Compare with scandir().
listxattr()
lockf()
lseek()
lstat()
major()
makedev()
makedirs()
Mapping
memfd_create()
MFD_ALLOW_SEALING
MFD_CLOEXEC
MFD_HUGE_16GB
MFD_HUGE_16MB
MFD_HUGE_1GB
MFD_HUGE_1MB
MFD_HUGE_256MB
MFD_HUGE_2GB
MFD_HUGE_2MB
MFD_HUGE_32MB
MFD_HUGE_512KB
MFD_HUGE_512MB
MFD_HUGE_64KB
MFD_HUGE_8MB
MFD_HUGE_MASK
MFD_HUGE_SHIFT
MFD_HUGETLB
minor()
mkdir()
mkfifo()
mknod()
MutableMapping
name The name of the operating system module (one of posix, nt, java). Compare with uname() and sys.platform
NGROUPS_MAX
nice()
O_ACCMODE
O_APPEND
O_ASYNC
O_CLOEXEC
O_CREAT
O_DIRECT
O_DIRECTORY
O_DSYNC
O_EXCL
O_LARGEFILE
O_NDELAY
O_NOATIME
O_NOCTTY
O_NOFOLLOW
O_NONBLOCK
O_PATH
open()
openpty()
O_RDONLY
O_RDWR
O_RSYNC
O_SYNC
O_TMPFILE
O_TRUNC
O_WRONLY
P_ALL
pardir
path
pathconf()
pathconf_names
PathLike
pathsep
pidfd_open()
pipe()
pipe2()
P_NOWAIT
P_NOWAITO
popen()
POSIX_FADV_DONTNEED
posix_fadvise()
POSIX_FADV_NOREUSE
POSIX_FADV_NORMAL
POSIX_FADV_RANDOM
POSIX_FADV_SEQUENTIAL
POSIX_FADV_WILLNEED
posix_fallocate()
posix_spawn()
POSIX_SPAWN_CLOSE
POSIX_SPAWN_DUP2
POSIX_SPAWN_OPEN
posix_spawnp()
P_PGID
P_PID
P_PIDFD
pread()
preadv()
PRIO_PGRP
PRIO_PROCESS
PRIO_USER
putenv()
P_WAIT
pwrite()
pwritev()
read()
readlink()
readv()
register_at_fork()
remove()
removedirs()
removexattr()
rename()
renames()
replace()
rmdir()
R_OK
RTLD_DEEPBIND
RTLD_GLOBAL
RTLD_LAZY
RTLD_LOCAL
RTLD_NODELETE
RTLD_NOLOAD
RTLD_NOW
RWF_DSYNC
RWF_HIPRI
RWF_NOWAIT
RWF_SYNC
scandir() Similar to listdir() but returns an iterator which returns posic.DirEntry objects. See also the shell command ls.
SCHED_BATCH
SCHED_FIFO
sched_getaffinity()
sched_getparam()
sched_get_priority_max()
sched_get_priority_min()
sched_getscheduler()
SCHED_IDLE
SCHED_OTHER
sched_param
SCHED_RESET_ON_FORK
SCHED_RR
sched_rr_get_interval()
sched_setaffinity()
sched_setparam()
sched_setscheduler()
sched_yield()
SEEK_CUR
SEEK_DATA
SEEK_END
SEEK_HOLE
SEEK_SET
sendfile()
sep
set_blocking()
setegid()
seteuid()
setgid()
setgroups()
set_inheritable()
setpgid()
setpgrp()
setpriority()
setregid()
setresgid()
setresuid()
setreuid()
setsid()
setuid()
setxattr()
spawnl()
spawnle()
spawnlp()
spawnlpe()
spawnv()
spawnve()
_spawnvef()
spawnvp()
spawnvpe()
st
ST_APPEND
stat()
stat_result
statvfs()
statvfs_result
ST_MANDLOCK
ST_NOATIME
ST_NODEV
ST_NODIRATIME
ST_NOEXEC
ST_NOSUID
ST_RDONLY
ST_RELATIME
strerror()
ST_SYNCHRONOUS
ST_WRITE
supports_bytes_environ
supports_dir_fd
supports_effective_ids
supports_fd
supports_follow_symlinks
symlink()
sync()
sys
sysconf()
sysconf_names
system()
tcgetpgrp()
tcsetpgrp()
terminal_size
times()
times_result
TMP_MAX
truncate()
ttyname()
umask()
uname() See also os.name, the platform module and the shell command uname.
uname_result
unlink()
unsetenv()
urandom()
utime()
wait()
wait3()
wait4()
waitid()
waitid_result
waitpid()
waitstatus_to_exitcode()
_walk()
walk()
WCONTINUED
WCOREDUMP()
WEXITED
WEXITSTATUS()
WIFCONTINUED()
WIFEXITED()
WIFSIGNALED()
WIFSTOPPED()
WNOHANG
WNOWAIT
W_OK
_wrap_close
write()
writev()
WSTOPPED
WSTOPSIG()
WTERMSIG()
WUNTRACED
XATTR_CREATE
XATTR_REPLACE
XATTR_SIZE_MAX
X_OK

Iterating over files and directory (os.listdir, os.scandir)

The functions os.listdir and os.scandir both allow to iterate (non-recursively) over files and directories in a given directory.
The functionality os.listdir() was improved by os.scandir().
As per PEP 0471, using os.scandir() can improve the performance.
os.listdir() returns bare filename strings.
os.scandir() returns DirEntry objects which also allow to query additional data for the individual files/directories, such as
Both, os.listdir() and os.scandir() skip the special directory entries . and ...
os.walk() might be used to iterate recursively.

Remove files and directories

Although Python has a built-in function to create files (open()), it does not have a built-in function to remove them. The functionality to remove files (and directories) is found in os:
In order to remove an entire directory tree, shutil.rmtree() can be used.
Note that the functions to check the existence of files and directories are located in the standard library os.path.

Create directories

The functions to create directories are

Print environment variables

The following script uses os.environ to print the environment variables that are defined in the current session.
Because the PATH environment variable is somewhat special because it consists of multiple paths, the script uses sys.path to print the list of directories that are searched for when trying to import a module.
import os
import sys

print("Defined environment variables:")
for var in os.environ:
    if var == 'PATH':
       sys.stdout.write ("  %-25s = " % var)
       path_iter = iter(sys.path)
       print(next(path_iter))  # print 1st path on same line as "PATH...="
       for dir in path_iter:   # print other paths indented:
           print((' ' * 30) + dir)
    else:
       print("  %-25s = %s  " % (var, os.environ[var]))

print('')
print("Expanded $HOME")
print("  " + os.path.expandvars('$HOME'))
Github repository about-python, path: /standard-library/os/environ.py

system

os.system(cmd) executes cmd in a subshell, using the standard C function system().
Consider replacing using os.system with functions found in the standard library module subprocess.

See also

os.walk() allows to iterate over subdirectories and files in them.
The os.path module has some functions related to files and filename manipulation.
The built-in function open() reads or writes files.
standard library

Index