os Python
Introduction
This module provides a portable way to use functionality that depends on the operating system.
If you just want to read or write a file, use
open()
, if you want to manipulate paths, use the module
os.path
, and if you want to read all lines in all files on the command line, use the fileinput module.
To create temporary files and directories use the tempfile module,
and for high-level processing of files and directories use the module
shutil
.
Articles that go well with this one:
Files in Linux
Basics of working with files in Python
Official documentation
getcwd() and chdir()
The current directory can be obtained with the method getcwd()
You can change to another directory with the method chdir()
import os # get current working directory print(os.getcwd()) # change directory os.chdir('/mnt/c/Users/Andrei/sandbox') print(os.getcwd())
/mnt/c/Users/Andrei/sandbox/python /mnt/c/Users/Andrei/sandbox
listdir()
The contents of a directory can be obtained with the method listdir()
import os # list directory contents print("os.listdir()") print(os.listdir())
os.listdir() ['php', 'python', 'test_complete']
Create a directory
A directory can be created with the methods mkdir() and makedirs()
import os # create dir without subdirs os.mkdir('urn.su') # create dir with subdirs os.makedirs('heihei.ru/Spain/travel') print("os.listdir()") print(os.listdir())
os.listdir() ['hehei.ru', 'php', 'python', 'test_complete', 'urn.su']
Delete a directory
A directory can be deleted with the methods rmdir() and removedirs()
import os # remove dir without subdirs os.rmdir('urn.su') # remove dir with subdirs os.removedirs('heihei.ru/Spain/travel') print("os.listdir()") print(os.listdir())
os.listdir() ['php', 'python', 'test_complete']
rename()
A file can be renamed with the method rename()
import os # rename file os.rename('test.txt', 'demo.txt') print("os.listdir()") print(os.listdir()) os.rename('demo.txt', 'test.txt') print("os.listdir()") print(os.listdir())
os.listdir() ['demo.txt', 'php', 'python', 'test_complete'] os.listdir() ['php', 'python', 'test.txt', 'test_complete']
os.stat()
import os os.chdir('/mnt/c/Users/Andrei/sandbox') # info print("os.stat('test.txt')") print(os.stat('test.txt')) # file size print("os.stat('test.txt').st_size") print(os.stat('test.txt').st_size) # modification time print("os.stat('test.txt').st_mtime") print(os.stat('test.txt').st_mtime)
os.stat('test.txt') os.stat_result(st_mode=33279, st_ino=48695170971005453, st_dev=47, st_nlink=1, st_uid=1000, st_gid=1000, st_size=0, st_atime=1683214359, st_mtime=1683214359, st_ctime=1683214612) os.stat('test.txt').st_size 0 os.stat('test.txt').st_mtime 1683214359.8984318
import os from datetime import datetime os.chdir('/mnt/c/Users/Andrei/sandbox') mod_time = os.stat('test.txt').st_mtime print(datetime.fromtimestamp(mod_time))
2026-11-17 21:15:39.098432
os.walk()
os.walk() returns an iterator whose elements are tuples of three elements: dirpath, dirname, filenames
Let us walk through the directory glob_ex from the article about glob
glob_ex/ ├── glob_ex.py ├── glob_ex1.py ├── glob_ex3.py ├── heihei │ ├── Armenia │ │ ├── holidays │ │ │ ├── easter.html │ │ │ └── sargis.html │ │ └── index.html │ ├── Finland.html │ ├── Spain.html │ └── Sweden.html ├── iglob_ex.py ├── sample_files │ ├── it.txt │ ├── testing.txt │ └── travel.txt └── topbicycle ├── forward.html ├── stark.html └── stels.html
import os from datetime import datetime path = '/mnt/c/Users/Andrei/sandbox/python/glob_ex/' os.chdir(path) walk = os.walk(path) print("next:", walk.__next__()) print("next:", walk.__next__()) print("next:", next(walk))
python os_walk_ex.py
next: ('/mnt/c/Users/Andrei/sandbox/python/glob_ex/', ['heihei', 'sample_files', 'topbicycle'], ['glob_ex.py', 'glob_ex1.py', 'glob_ex3.py', 'iglob_ex.py']) next: ('/mnt/c/Users/Andrei/sandbox/python/glob_ex/heihei', ['Armenia'], ['Finland.html', 'Spain.html', 'Sweden.html']) next: ('/mnt/c/Users/Andrei/sandbox/python/glob_ex/heihei/Armenia', ['holidays'], ['.hidden.html', 'index.html'])
import os from datetime import datetime path = '/mnt/c/Users/Andrei/sandbox/python/glob_ex/' os.chdir(path) for dirpath, dirnames, filenames in os.walk(path): print('Current Path:', dirpath) print('Directories:', dirnames) print('Files:', filenames) print()
python os_walk_ex.py
Current Path: /mnt/c/Users/Andrei/sandbox/python/glob_ex/ Directories: ['heihei', 'sample_files', 'topbicycle'] Files: ['glob_ex.py', 'glob_ex1.py', 'glob_ex3.py', 'iglob_ex.py'] Current Path: /mnt/c/Users/Andrei/sandbox/python/glob_ex/heihei Directories: ['Armenia'] Files: ['Finland.html', 'Spain.html', 'Sweden.html'] Current Path: /mnt/c/Users/Andrei/sandbox/python/glob_ex/heihei/Armenia Directories: ['holidays'] Files: ['.hidden.html', 'index.html'] Current Path: /mnt/c/Users/Andrei/sandbox/python/glob_ex/heihei/Armenia/holidays Directories: [] Files: ['easter.html', 'sargis.html'] Current Path: /mnt/c/Users/Andrei/sandbox/python/glob_ex/sample_files Directories: [] Files: ['it.txt', 'testing.txt', 'travel.txt'] Current Path: /mnt/c/Users/Andrei/sandbox/python/glob_ex/topbicycle Directories: [] Files: ['forward.html', 'stark.html', 'stels.html']
os.environ()
import os print(os.environ.get("HOME"))
/home/andrei
os.path()
os.path.join() saves you from having to think about whether to put a slash in the
path or not, and also which slash to put depending on the OS.
An example of using os.path.join()
you can study in the article
shutil
Another example of using os.path() you can also study in the article
«Packages in Python»
import os file_path = os.path.join(os.environ.get("HOME"), "test.txt") print(file_path) with open(file_path, "w") as f: f.write("")
python os_path_ex.py
/home/andrei/test.txt
Let us check that the file was created in the home directory.
ls ~
test.txt
path has rather extensive functionality.
import os file_path = os.path.join(os.environ.get("HOME"), "test.txt") print(os.path.basename(file_path))
test.txt
The name of the directory containing the file can be obtained with dirname
print(os.path.dirname(file_path))
/home/andrei
Separating the file name from the full path is helped by split, and splitext will separate the file extension from everything else.
print(os.path.split(file_path)) print(os.path.splitext(file_path))
('/home/andrei', 'test.txt') ('/home/andrei/test', '.txt')
Checking whether a path exists is helped by exists().
An alternative way of this check is to use
Path.exists()
from the library
pathlib
To determine whether a file is a directory or a regular file, use
isdir and isfile.
If you
work with files
in
Linux
I recommend reading
this article
print(os.path.exists(file_path)) print(os.path.exists("/tmp/random.txt")) print(os.path.isdir(file_path)) print(os.path.isdir("/home")) print(os.path.isfile(file_path)) print(os.path.isfile("/home"))
True False False True True False
A practical example of using isfile you can study in the article shutil
The list of all attributes of os.path can be obtained with the function dir()
print(dir(os.path))
['__all__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_get_sep', '_joinrealpath', '_path_normpath', '_varprog', '_varprogb', 'abspath', 'altsep', 'basename', 'commonpath', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep', 'split', 'splitdrive', 'splitext', 'stat', 'supports_unicode_filenames', 'sys']
dir()
The list of all attributes of os can be obtained with the function dir()
import os print(dir(os))
python os_ex.py
['CLD_CONTINUED', 'CLD_DUMPED', 'CLD_EXITED', 'CLD_KILLED', 'CLD_STOPPED', 'CLD_TRAPPED', 'DirEntry', 'EFD_CLOEXEC', 'EFD_NONBLOCK', 'EFD_SEMAPHORE', 'EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_LOCK', 'F_OK', 'F_TEST', 'F_TLOCK', 'F_ULOCK', 'GRND_NONBLOCK', 'GRND_RANDOM', 'GenericAlias', 'MFD_ALLOW_SEALING', 'MFD_CLOEXEC', 'MFD_HUGETLB', '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', 'Mapping', 'MutableMapping', 'NGROUPS_MAX', 'O_ACCMODE', 'O_APPEND', 'O_ASYNC', 'O_CLOEXEC', 'O_CREAT', 'O_DIRECT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_FSYNC', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_PATH', 'O_RDONLY', 'O_RDWR', 'O_RSYNC', 'O_SYNC', 'O_TMPFILE', 'O_TRUNC', 'O_WRONLY', 'POSIX_FADV_DONTNEED', 'POSIX_FADV_NOREUSE', 'POSIX_FADV_NORMAL', 'POSIX_FADV_RANDOM', 'POSIX_FADV_SEQUENTIAL', 'POSIX_FADV_WILLNEED', 'POSIX_SPAWN_CLOSE', 'POSIX_SPAWN_DUP2', 'POSIX_SPAWN_OPEN', 'PRIO_PGRP', 'PRIO_PROCESS', 'PRIO_USER', 'P_ALL', 'P_NOWAIT', 'P_NOWAITO', 'P_PGID', 'P_PID', 'P_PIDFD', 'P_WAIT', 'PathLike', 'RTLD_DEEPBIND', 'RTLD_GLOBAL', 'RTLD_LAZY', 'RTLD_LOCAL', 'RTLD_NODELETE', 'RTLD_NOLOAD', 'RTLD_NOW', 'RWF_APPEND', 'RWF_DSYNC', 'RWF_HIPRI', 'RWF_NOWAIT', 'RWF_SYNC', 'R_OK', 'SCHED_BATCH', 'SCHED_FIFO', 'SCHED_IDLE', 'SCHED_OTHER', 'SCHED_RESET_ON_FORK', 'SCHED_RR', 'SEEK_CUR', 'SEEK_DATA', 'SEEK_END', 'SEEK_HOLE', 'SEEK_SET', 'SPLICE_F_MORE', 'SPLICE_F_MOVE', 'SPLICE_F_NONBLOCK', 'ST_APPEND', 'ST_MANDLOCK', 'ST_NOATIME', 'ST_NODEV', 'ST_NODIRATIME', 'ST_NOEXEC', 'ST_NOSUID', 'ST_RDONLY', 'ST_RELATIME', 'ST_SYNCHRONOUS', 'ST_WRITE', 'TMP_MAX', 'WCONTINUED', 'WCOREDUMP', 'WEXITED', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WNOWAIT', 'WSTOPPED', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'XATTR_CREATE', 'XATTR_REPLACE', 'XATTR_SIZE_MAX', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_check_methods', '_execvpe', '_exists', '_exit', '_fspath', '_fwalk', '_get_exports_list', '_spawnvef', '_walk', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 'copy_file_range', 'cpu_count', 'ctermid', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'environb', 'error', 'eventfd', 'eventfd_read', 'eventfd_write', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fchmod', 'fchown', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'fwalk', 'get_blocking', 'get_exec_path', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getegid', 'getenv', 'getenvb', 'geteuid', 'getgid', 'getgrouplist', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getpriority', 'getrandom', 'getresgid', 'getresuid', 'getsid', 'getuid', 'getxattr', 'initgroups', 'isatty', 'kill', 'killpg', 'lchown', 'linesep', 'link', 'listdir', 'listxattr', 'lockf', 'login_tty', 'lseek', 'lstat', 'major', 'makedev', 'makedirs', 'memfd_create', 'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open', 'openpty', 'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep', 'pidfd_open', 'pipe', 'pipe2', 'popen', 'posix_fadvise', 'posix_fallocate', 'posix_spawn', 'posix_spawnp', 'pread', 'preadv', 'putenv', 'pwrite', 'pwritev', 'read', 'readlink', 'readv', 'register_at_fork', 'remove', 'removedirs', 'removexattr', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sched_get_priority_max', 'sched_get_priority_min', 'sched_getaffinity', 'sched_getparam', 'sched_getscheduler', 'sched_param', 'sched_rr_get_interval', 'sched_setaffinity', 'sched_setparam', 'sched_setscheduler', 'sched_yield', 'sendfile', 'sep', 'set_blocking', 'set_inheritable', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setpriority', 'setregid', 'setresgid', 'setresuid', 'setreuid', 'setsid', 'setuid', 'setxattr', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'splice', 'st', 'stat', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', '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', 'truncate', 'ttyname', 'umask', 'uname', 'uname_result', 'unlink', 'unsetenv', 'urandom', 'utime', 'wait', 'wait3', 'wait4', 'waitid', 'waitid_result', 'waitpid', 'waitstatus_to_exitcode', 'walk', 'write', 'writev']
Article author: Andrei Olegovich